Category Archives: Asp.Net Core

Global exception handling in asp.net core

Global exception handling is a way to handle unhandled exceptions in asp.net core.

Add a middleware UseExceptionHandler to the pipeline that will catch exceptions, log them, reset the request path and re-execute the request. The request will not be re-executed if the response has already started.

Add UseExceptionHandler code in Startup.Configure method as stated below. This will redirect to Error action.

if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/Error");
     }

Now exception can be captured using IExceptionHandlerFeature in the Error Action.

 Public IActionResult Error()
 {    
     var errorFeature = HttContext.Features.Get<IExceptionHandlerFeature>();
     var error = errorFeature.Error;
     var errorMessage= error.Message;
     var errorStackTrace = error.StackTrace;
     return View();
 }

TempData is null in asp.net core

The TempData provider cookie isn’t essential. CheckConsentNeeded is used to get user permission to enable cookies. If user has denied cookies then TempData cookies will not be provided to browser.

In Asp.Net Core 2.1 to enable TempData cookies disable the CheckConsentNeeded option in Startup.ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure.CookiePolicyOptions(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            // options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
}

Asp.Net Core 2.2 has provided a new feature to configure the non-essential cookies even user has denied the cookie tracking permission. Add IsEssential property in Startup.ConfigureServices method as below.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure.CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.Cookie.IsEssential = true;
            options.MinimumSameSitePolicy = SameSiteMode.None;

        });
}

How to disable camel case in asp.net core?

In dotnet core default case for serializing output to json is camelCase. We can change the default case to Pascal by setting the new DefaultContractResolver

Steps

  1. Go to Startup.cs class file.
  2. Find Startup.ConfigureServices method and add the below line of code.
public void ConfigureServices(IServiceCollection services)
{
    // Add Services
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}