使用Custom访问ASP.NET Core中的当前HttpContext

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

我正在编写以下代码:Access the current HttpContext in ASP.NET Core

我收到错误。我该如何解决这个问题?另外,接口IMyComponent的代码是什么?只是想确定它的正确性。

错误:

类型或命名空间IMyComponent无法找到名称“KEY”在当前上下文中不存在。

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

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

    public string GetDataFromSession()
    {
        return _contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}
c# asp.net-core .net-core asp.net-core-mvc .net-core-2.0
1个回答
0
投票

您需要注意的一些要点:

1.您的类继承自接口并实现GetDataFromSession方法。您需要先定义一个接口IMyComponent并在staryup中注册IMyComponent如果您想要使用DI

public interface IMyComponent
{
    string GetDataFromSession();
}

startup.cs

services.AddSingleton<IMyComponent, MyComponent>();

2.好像你想从会话中获取数据。 “Key”表示任何会话名称(字符串)。您需要为asp.net核心enable session并首先设置会话值。

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

3.在你的创业公司注册IHttpContextAccessor

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

4.完整的演示:

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;

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