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*);
    }
}
trashr0x
  • 6,457
  • 2
  • 29
  • 39
  • Please provide a [mcve]. `*KEY*` is NOT valid C#. – ProgrammingLlama Mar 21 '19 at 07:01
  • I received the code from stack overflow question above, guess my question is what should be *Key*? –  Mar 21 '19 at 07: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. – smoksnes Mar 21 '19 at 07:05
  • 1
    I'd recommend checking out the [docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#set-and-get-session-values). `Key`should be a string identifying the item you have saved into the session. `IMyComponent` is your interface for `MyComponent`. – ProgrammingLlama Mar 21 '19 at 07:05
  • Do you add setting for MyComponent and IMyComponent in Dependency Injection block? – Roma Ruzich Mar 21 '19 at 07:20

1 Answers1

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;

    }
Ryan
  • 19,118
  • 10
  • 37
  • 53