从 ASP.NET Core Razor 项目的 cookie 初始化单例

问题描述 投票:0回答:1

我是使用 ASP.NET 8 和 Razor 开发 Web 应用程序的新手,我花了几个小时尝试将我的 Windows 应用程序移植到 Web。我根本无法理解如何使一些非常简单的事情发挥作用:

在我的应用程序中,我有一个从配置文件读取的 appSetting 类。我的应用程序中都使用了此设置。现在我想要为我的网络应用程序提供类似的东西,但我不断遇到各种我没有得到的东西。

我创建了“appSetting”类并将其作为单例添加到 Program.cs 中:

builder.Services.AddSingleton<AppSetting>();

然后我认为我需要在某个地方初始化它,并且我尝试在“index.cshtml.cs”文件中执行此操作。

private readonly AppSetting _appSetting;

public string appVersion => _appSetting.version;

public IndexModel(ILogger<IndexModel> logger)
{
   _logger = logger;
   _appSetting = new AppSetting();
}

在我的类的构造函数中,我尝试读取 cookie,但这只会引发运行时错误:System.NullReferenceException:“对象引用未设置为对象的实例。”

public AppSetting()
{
   var cookies = Request.Cookies["version"];
}

我根本不知道如何实现我想要的。

提前致谢

拉尔斯·博

asp.net class cookies razor
1个回答
0
投票

我使用这种方法在我的应用程序中实现这一目标

 using Microsoft.Extensions.Options;

 public static class IocExtensions
    {
        public static void AddConfiguration<TInterface, T>(this IServiceCollection services, string? configurationName = null)
            where T : class, TInterface
        {
            AddConfiguration<T>(services, configurationName);
            RegisterByType<TInterface, T>(services);
        }
    
        public static void AddConfiguration<T>(this IServiceCollection services, string? configurationName = null)
            where T : class
        {
            services.AddOptions<T>()
                    .BindConfiguration(configurationName ?? typeof(T).Name)
                    .ValidateDataAnnotations()
                    .ValidateOnStart();
    
            RegisterByType<T, T>(services);
        }
    
        private static void RegisterByType<TInterface, T>(IServiceCollection services)
            where T : class, TInterface
        {
            services.AddSingleton(typeof(TInterface), provider => provider.GetRequiredService<IOptions<T>>().Value);
        }
    } 

我就是这么用的

builder.Services.AddConfiguration<IMyConfiguration, MyConfiguration>();

这就是模型

public interface IMyConfiguration
{
   string MyProp { get; }
}

public class MyConfiguration: IMyConfiguration
{
    public required string MyProp { get;init; }
}

为了解析您需要在 appsettings.json 中包含的所有内容

"MyConfiguration": {
    "MyProp": ""
  }

这就是我使用它的方式,还有一些更简单的解决方案,我在堆栈溢出中找到了this

© www.soinside.com 2019 - 2024. All rights reserved.