I have an ASP.net 5.0 website (MVC 6) and use this site for some mobile applications. I have a controller that returns json data.
The user must authenticate to view this data, so I use the [Authorize] attribute for the controller.
I was expecting to get error 401 for unauthorized requests. I get a redirect (302) to the login page. In the mobile client, set the header only to receive "application / json" data, but I still get a redirect to the login page.
I developed a solution that works, but I'm not very happy with it. It works, but it's a kind of hack.
Is there a better solution for this?
Here is my solution (Configure method in Startup class)
//....Some Code app.Use(async (context, next) => { await next.Invoke(); if (context.Response.StatusCode == 302) { StringValues contentType; if (context.Request.Headers.TryGetValue("Accept", out contentType) && contentType.Contains("application/json")) { context.Response.StatusCode = 401; if (env.IsDevelopment()) await context.Response.WriteAsync("No Access"); } } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
source share