How to return 401 instead of 302 in ASP.NET Core
By Tan Lee Published on Jun 10, 2024 1.22K
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.
- Implement security headers for an ASP.NET Core
- How to add security headers to an ASP.NET Core Application
- How to Initialize TagHelpers in ASP.NET Core with Shared Data
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
Categories
Popular Posts
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
Implement security headers for an ASP.NET Core
Jun 24, 2025
What Are RESTful Web Services?
Feb 19, 2024
Plus Admin Dashboard Template
Nov 18, 2024