如何防止ASP.NET MVC 5将用户重定向到登录页面?

时间:2017-11-07 21:47:02

标签: c# asp.net asp.net-mvc redirect asp.net-mvc-5

我有一个使用c#编写的ASP.NET MVC 5应用程序。一些端点用于应用程序本身,而其他端点仅用于API调用。 API端点返回JsonResult

我希望API始终返回JSON,而不是在用户未登录或用户未经授权时重定向。

所以我创建了一个名为ApiAuthorizeAttribute的新Authorize-Attribute,我只在我的API端点上使用它。

以下是ApiAuthorizeAttribute类的外观

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            int httpCode = (int)System.Net.HttpStatusCode.Unauthorized;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            filterContext.HttpContext.Response.StatusCode = httpCode;
            filterContext.HttpContext.Response.ContentType = "application/json";
            filterContext.HttpContext.Response.Write(JsonConvert.SerializeObject(
                new BaseResource(false, httpCode, "Request Forbidden. You must first login!")
                )
            );
            //filterContext.HttpContext.Response.End();

            filterContext.Result = new HttpStatusCodeResult(httpCode);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }                
    }
}

但是,即使用户未经授权,框架仍会将用户重定向到我试图避免的登录页面。我可以看到请求转到我的代码的if(!filterContext.HttpContext.Request.IsAuthenticated){...}部分,它仍然会将用户重定向到登录页面。

更新

如果我取消注释filterContext.HttpContext.Response.End();行并使用Visual Studio逐步执行代码。该页面正确显示我的JSON。但是当代码完成调用控制器中的“Dispose()”方法时,我的浏览器出现The connection was reset错误,这似乎是某种重定向错误。

如何正确阻止框架重定向用户?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。这是因为我返回401错误代码。所以这就是我将代码改为

的原因
m = matrix(c(5, 195, 2, 198), nrow = 2)

diag(m) # This gives the main diagonal (5 and 198) but I need the opposite diagonal?