没有显式登录的ASP.NET登录重定向

时间:2012-08-20 19:11:17

标签: asp.net ajax asp.net-mvc asp.net-ajax

使用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调用的检查似乎有效,唯一奇怪的是,在catch之后,登录页面仍然是作为响应发送的。我已经检查了FormsAuthentication方法的所有用法,以确保没有其他人强制FormsAuthentication.RedirectToLoginPage()并检查,事实上,所有使用FormsAuthentication都没有做任何奇怪的事情。我还检查了登录页面网址的查询(通过GetRedirectUrl()),但仍未查看。

有没有人有什么想法会做autoredirect?

1 个答案:

答案 0 :(得分: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
 }