Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ignas-sakalauskas/966daf32ad8396ceb62bb434e1098701 to your computer and use it in GitHub Desktop.
Save ignas-sakalauskas/966daf32ad8396ceb62bb434e1098701 to your computer and use it in GitHub Desktop.
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