Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
IHttpContextAccessor and Exceptions handling
public class TestDataService
{
private readonly IHttpContextAccessor _httpContextAccessor;
// Inject IHttpContextAccessor into constructor
public TestDataService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public string GetTestValue()
{
return _httpContextAccessor.HttpContext.Session.GetString("testKey");
}
}
// https://ignas.me/tech/ihttpcontextaccessor-exceptions-handling/
[Route("[controller]")]
public class ErrorController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
public ErrorController(IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory)
{
_httpContextAccessor = httpContextAccessor;
_logger = loggerFactory?.CreateLogger(nameof(ErrorController)) ?? throw new ArgumentNullException(nameof(loggerFactory));
}
[Route("")]
public IActionResult Index()
{
// Get exception from the context using IExceptionHandlerFeature.
var exception = _httpContextAccessor.HttpContext.Features.Get<IExceptionHandlerFeature>();
if (exception != null)
{
_logger.LogError(1, exception.Error, "Unhandled exception occurred.");
}
return View("Index");
}
}
// https://ignas.me/tech/ihttpcontextaccessor-exceptions-handling/
public void ConfigureServices(IServiceCollection services)
{
// Register IHttpContextAccessor with DI
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Add Session
services.AddSession();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(_configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Send all unhandled exceptions to Error controller
app.UseExceptionHandler("/Error");
app.UseStaticFiles();
app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.