How to return 401 instead of 302 in ASP.NET Core
By FoxLearn 2/15/2024 4:31:06 AM 65
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
- How to fix "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'"
- How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'
- ASP.NET Core: How to Create RDLC Report in ASP.NET Core
- How to fix Assets file 'project.assets.json' not found
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
- How to set cookie ValidationInterval in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
- How to fix Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager'
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024