ASP.net 5.0 - WebAPI授权和ErrorCode 302而不是401

Rom*_*man 5 c# asp.net asp.net-web-api asp.net-core-mvc

我有一个ASP.net 5.0(MVC 6)网站,也使用这个网站的一些移动应用程序.我有一个返回json数据的控制器.

用户必须进行身份验证才能看到此数据,因此我使用Controller的[Authorize]属性.

我希望在未经授权的请求中获得错误401,我得到重定向(302)到登录页面.在Mobile Client中,将标头设置为仅接受"application/json"数据,但我仍然可以重定向到登录页面.

我开发了一个有效的解决方案,但我对此并不满意.它有效,但它是一种黑客攻击.

有没有更好的解决方案来处理这个问题?

这是我的解决方案(Startup类中的Configure方法)

        //....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?}");
        });
Run Code Online (Sandbox Code Playgroud)

小智 4

这应该由客户解决。客户端必须发送X-Requested-With带有 value 的标头XMLHttpRequest

所以这应该是 HTTP 请求中标头部分的一部分:

X-Requested-With: XMLHttpRequest
Run Code Online (Sandbox Code Playgroud)

现在您无需破解即可获得 401。