阻止ASP.NET重定向到login.aspx

时间:2013-08-29 19:25:48

标签: asp.net asp.net-mvc .htaccess angularjs

我们有一个完全在AngularJS上运行的网站,其ASP.NET Web API后端具有以下配置: - 在Angular上启用了HTML5路由,并且web.config中有一个重写规则,用于将所有流量定向到index.html - 未安装MVC(仅限剃刀页面) - 使用表单身份验证和相关cookie进行身份验证

我刚刚添加了Helicon IIS插件,为我们的开发服务器提供了.htaccess密码保护(单独使用IIS是一件麻烦事)但我有一个基本问题。

输入基本身份验证凭据后,我将重定向到/login.aspx?ReturnUrl=,虽然我不确定由谁(IIS或Helicon插件)负责,但它会匹配我的一个AngularJS路由和导致错误。

如何阻止此重定向发生?

我的web.config身份验证位:

<authentication mode="Forms">
  <forms protection="All" timeout="15" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="false" cookieless="UseCookies" enableCrossAppRedirects="false" />
</authentication>

2 个答案:

答案 0 :(得分:14)

如果您使用的是ASP.NET 4.5。 您可以禁用表单身份验证重定向 HttpResponse.SuppressFormsAuthenticationRedirect属性。

在Global.asax中:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
        HttpApplication context = (HttpApplication)sender;
        context.Response.SuppressFormsAuthenticationRedirect = true;
}

答案 1 :(得分:5)

总之,我把它放在global.asax

JFactory::getDocument()->addScriptDeclaration('
$(document).ready(function(){
$(\'[data-toggle="tooltip"]\').tooltip();   
});

');

protected void Application_BeginRequest(object sender, EventArgs e) { var context = new HttpContextWrapper(Context); // set flag only if forms auth enabled and request comes from ajax if (FormsAuthentication.IsEnabled && context.Request.IsAjaxRequest()) { context.Response.SuppressFormsAuthenticationRedirect = true; } } 使用此

IsAjaxRequest()

因此,对于每个ajax请求表单,auth将不再重定向。这是我找到的最佳解决方案。

并且可选地,将其放在客户端代码中,以便在收到401错误答案后重新加载页面。

public static bool IsAjaxRequest(this HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    var context = HttpContext.Current;
    var isCallbackRequest = false;// callback requests are ajax requests
    if (context != null && context.CurrentHandler is Page)
    {
        isCallbackRequest = ((Page)context.CurrentHandler).IsCallback;
    }
    return isCallbackRequest || request["X-Requested-With"] == "XMLHttpRequest" || 
        request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
相关问题