How to return 401 instead of 302 in ASP.NET Core

By FoxLearn 6/10/2024 7:32:30 AM   139
Sometimes you add an [Authorize] attribute to your web API method in ASP.NET Core 2.0 and instead of returning 401, it returns 302.

To return a 401 status code instead of a 302 in ASP.NET Core, you'll typically handle it in the middleware or controller logic. A 401 status code indicates unauthorized access, whereas a 302 status code is a redirection.

Here's a basic example of how you might return a 401 status code in ASP.NET Core middleware.

I'll create a GetAll action to retrieve the Invoice data, then return json data.

[HttpGet, Authorize]
public IActionResult GetAll()
{
    try
    {
        using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DefaultConnection")))
        {
            if (db.State == ConnectionState.Closed)
                db.Open();
            List<Invoice> invoices = db.Query<Invoice>("SELECT *FROM dbo.[Invoice]").ToList();
            return Json(new { result = invoices });
        }
    }
    catch (Exception ex)
    {
        return Json(new { result = ex.Message });
    }
}

To solve the problem return a 401 status code instead of a 302, you need to modify the middleware in your Startup.cs file.

services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = new PathString("/Account/Login");
options.LogoutPath = new PathString("/Account/Logout");
options.Events.OnRedirectToLogin = context =>
                {
                    if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == StatusCodes.Status200OK)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        return Task.FromResult<object>(null);
                    }
                    context.Response.Redirect(context.RedirectUri);
                    return Task.FromResult<object>(null);
                };
            });

This middleware will intercept incoming requests and return a 401 status code if the user is not authenticated.