I have a ASP.net 5.0 (MVC 6) Website and use this website also for some mobile apps. I have a controller that returns json data.
The User has to Authenticate to see this data so I use the [Authorize] attribute for the Controller.
I expected to get an Error 401 for not authorized requests nur I get an redirect (302) to the loginpage. In the Mobile Client a set the header to only accept "application/json" data but I still get the redirect to the login page.
I developed an solution that works but I'm not very happy with it. It works but it is a kind of hack.
Is there a better solution to handle this?
Here 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?}");
        });
                This should be solved by the client. The client have to send a X-Requested-With header with the value XMLHttpRequest.
So this should be a part of the headers section in the HTTP request:
X-Requested-With: XMLHttpRequest
Now you'll get your 401's without hacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With