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

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.

That's a problem i'm going to show you how to fix it.

[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 above, you need to open the Startup class, then modify your config as below

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

I hope the above code can solve your problem