geo*_*osd 6 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>
Run Code Online (Sandbox Code Playgroud)
Oua*_*ATA 16
如果您使用的是ASP.NET 4.5.您可以禁用表单身份验证重定向HttpResponse.SuppressFormsAuthenticationRedirect属性.
在Global.asax中:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication context = (HttpApplication)sender;
context.Response.SuppressFormsAuthenticationRedirect = true;
}
Run Code Online (Sandbox Code Playgroud)
总之,我把它放在global.asax中
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;
}
}
Run Code Online (Sandbox Code Playgroud)
并IsAjaxRequest()用于此
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";
}
Run Code Online (Sandbox Code Playgroud)
所以对于每个ajax请求表单,auth将不再重定向.这是我发现的最佳解决方案.
并且可选地,将其放在客户端代码中,以便在收到401错误答案后进行页面重新加载.
$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {
location.reload();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10845 次 |
| 最近记录: |