How to return 401 instead of 302 in ASP.NET Core
By Tan Lee Published on Jun 10, 2024 944
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.
- 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
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Gentella Admin Template
Nov 14, 2024
Focus Admin Dashboard Template
Nov 18, 2024