使用自定义访问 ASP.NET Core 中的当前 HttpContext

Access the current HttpContext in ASP.NET Core with Custom

我正在编写以下代码:

我收到错误消息。我将如何解决这个问题? 另外,Interface IMyComponent 的代码是什么?只是想确定它是正确的。

错误:

Type or namespace IMyComponent Cannot be found The Name 'KEY' does not exist in current context.

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public string GetDataFromSession()
    {
        return _contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}

需要注意的几点:

1.You class 继承一个接口并实现一个 GetDataFromSession method.You 需要先定义一个接口 IMyComponent 并注册 IMyComponent如果您想使用 DI

,请在 staryup
public interface IMyComponent
{
    string GetDataFromSession();
}

startup.cs

services.AddSingleton<IMyComponent, MyComponent>();

2.It 看来您想从会话中获取数据。 "Key" 代表任何会话名称(字符串)。您需要enable session for asp.net core 并先设置一个会话值。

_contextAccessor.HttpContext.Session.SetString("Key", "value");

3.Register IHttpContextAccessor 在你的启动中

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

4.Full 演示:

MyComponent.cs

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public string GetDataFromSession()
    {

        _contextAccessor.HttpContext.Session.SetString("Key", "value");
        return _contextAccessor.HttpContext.Session.GetString("Key");
    }
}

public interface IMyComponent
{
    string GetDataFromSession();
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<IMyComponent, MyComponent>();
    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //other middlewares
        app.UseSession();           
        app.UseMvc();
    }
}

API 控制器:

public class ForumsController : ControllerBase
{
    private readonly IMyComponent _myComponent;

    public ForumsController(IMyComponent myComponent)
    { 
        _myComponent = myComponent;
    }
    // GET api/forums
    [HttpGet]
    public ActionResult<string> Get()
    {
        var data = _myComponent.GetDataFromSession();//call method and return "value"
        return data;

    }