How to return 401 instead of 302 in ASP.NET Core
By FoxLearn 6/10/2024 7:32:30 AM 848
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.
- 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
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Regal Admin Dashboard Template
11/18/2024
Motiv MUI React Admin Dashboard Template
11/19/2024