0

I am writing code for following: Access the current HttpContext in ASP.NET Core

I am receiving error. How would I resolve this? Also, whats the code for Interface IMyComponent? Just want to be sure its correct.

Errors:

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*);
    }
}
5
  • Please provide a minimal reproducible example. *KEY* is NOT valid C#. Commented Mar 21, 2019 at 7:01
  • I received the code from stack overflow question above, guess my question is what should be Key? Commented Mar 21, 2019 at 7:02
  • Based on your question I think that you don't need GetString(). You should be able to do just fine with _contextAccessor.HttpContext if it is the HttpContext you want. The example simply shows how you can access a string stored in Session. Commented Mar 21, 2019 at 7:05
  • 1
    I'd recommend checking out the docs. Keyshould be a string identifying the item you have saved into the session. IMyComponent is your interface for MyComponent. Commented Mar 21, 2019 at 7:05
  • Do you add setting for MyComponent and IMyComponent in Dependency Injection block? Commented Mar 21, 2019 at 7:20

1 Answer 1

1

Some points you need to pay attention to:

1.You class inherit from an interface and implement a GetDataFromSession method.You need to define an interface IMyComponent first and register IMyComponent in staryup if you would like use by DI

public interface IMyComponent
{
    string GetDataFromSession();
}

startup.cs

services.AddSingleton<IMyComponent, MyComponent>();

2.It seems that you would like to get data from session. The "Key" represents any session name (string).You need to enable session for asp.net core and set a session value first.

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

3.Register IHttpContextAccessor in your startup

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

4.Full demo:

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 Controller:

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;

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.