3

带有 MVC 3.0 的 ASP .NET 4.0

所以情况是这样的:我是 MVC 和 ASP.NET 的新手,我有一个 MVC 应用程序,它在web.config中使用 FormAuthentication 和以下内容:

<authentication mode="Forms">
   <forms loginUrl="~/LogOn/LogOn" timeout="2" requireSSL="true" />
</authentication>

通常发生的情况是,如果用户在会话过期后导航到某个页面,他们会被定向到 LogOn 页面,这很好。如果请求是 Ajax 调用,我想要做的是防止该页面被发回,而是发回一个 JSON 对象以指示失败。
我已经捕获了请求,通过以下方式检查 XMLHttp 类型:

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
        if (s_identityProvider == null)
            return;
        IClaimsPrincipal principal = GetClaimsPrincipal();
        Context.User = principal;
        if (principal != null)
            ClaimProvider.CheckAndPopulateRoles(principal);
        else
        {
            if (Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                Context.Response.Write( "<?xml version='1.0' encoding='ISO-8859-1'?>"+
                                        "<note>"+
                                        "</note>";
            }
            else
            {
                FormsAuthentication.SignOut();
            }
        }
}

现在,我测试了我对 AJAX 调用的检查似乎有效,唯一奇怪的是在捕获之后,登录页面仍然作为响应发送。我已经检查了 FormsAuthentication 方法的所有用途,以确保没有其他人强制使用 aFormsAuthentication.RedirectToLoginPage()并检查了,事实上,FormsAuthentication 的所有用途都没有做任何奇怪的事情。我还检查了登录页面 URL(通过GetRedirectUrl())的查询,但仍然没有。

有谁知道自动重定向会做什么?

4

1 回答 1

0

我唯一的猜测是该AuthenticateRequest方法不是这里请求生命周期的结束。因此,Response最终返回给用户的是重定向响应。您应该尝试在捕获并修改 AJAX 响应后显式结束,Response以避免 MVC 框架进一步操作

if (Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
    Context.Response.Write( "<?xml version='1.0' encoding='ISO-8859-1'?>"+
                            "<note>"+
                            "</note>";
    Context.Response.End(); // Calling End here should complete the response.
 }
 else {
            // ... other stuff
 }
于 2012-08-20T19:17:50.363 回答