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;
}