How to return 401 instead of 302 in ASP.NET Core
By FoxLearn 6/10/2024 7:32:30 AM 258
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.
- Getting Started with ASP.NET Core 3.0
- How to fix 'Authorization in ASP.NET Core' with 401 Unauthorized
- The name 'Session' does not exist in the current context
- How to create a Toast Notifications in ASP.NET Core
- How to Minify HTML using WebMarkupMin in ASP.NET Core
- How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
Categories
Popular Posts
How to sign a powershell script
10/03/2024
How to get Credentials in PowerShell?
10/03/2024
How to implement Jint in C#
09/14/2024