我想出了什么是问题,而不是IIS …看到我的回答下面的结果.
原始问题
我正在开发一个ASP.Net MVC应用程序,并运行到一个奇怪的问题与URL Rewrite重定向和AJAX请求.
我已经在根网站中的Web.config中添加了以下重写规则.
<rewrite>
<rules>
<rule name="Account" stopProcessing="true">
<match url="^SubApp/Account/(.*)$" />
<action type="Redirect" url="Account/{R:1}" redirectType="Found" />
</rule>
</rules>
</rewrite>
如果我在配置中使用永久或临时redirectType,但是出现HTTP错误401.0 – 未经授权的IIS错误页面失败,所有似乎都可以正常工作.
当我通过浏览器进行正常的GET请求时,可以触发此规则的操作. https:// some-site / SubApp / Account / Settings然后我找到302找到并且位置标题设置为预期的URL https:// some-site / Account / Settings,并且渲染相应的页面.
然而,当我通过JQuery的AJAX(即$.get(‘https:// some-site / SubApp / Account / Settings))发出GET请求时,返回的响应状态代码为401未授权,但仍具有相应的位置标题.
响应的内容是标准的IIS HTTP错误401.0 – 未经授权的错误页面.
奇怪的是,如果我使用配置中的永久或临时重定向类型,但是仅在Found中失败,所有似乎都可以正常工作.
/ SubApp是一个单独的应用程序,位于/的根站点下方.
这是怎么回事?
截图
redirectType = “永久”
redirectType = “找到”
redirectType = “临时”
从屏幕截图可以看出,唯一的区别是在Web.config中指定的redirectType.
正如你可以看到重定向正如预期的那样发生,找到重定向类型,我会期望得到一个302找到的响应重定向到与其他URL相同的URL.
protected void Application_EndRequest()
{
var context = new HttpContextwrapper(Context);
// MVC retuns a 302 for unauthorized ajax requests so alter to request status to be a 401
if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest() && !context.Request.IsAuthenticated)
{
context.Response.Clear();
context.Response.StatusCode = 401;
}
}
而且,毫无疑问,context.Request.IsAuthenticated总是为false,因为它似乎被重定向重置.
更新了这个,从Branislav Abadjimarinov’s blog post的一点帮助.
protected void Application_EndRequest()
{
var context = new HttpContextwrapper(Context);
// MVC returns a 302 for unauthorized ajax requests so alter to request status to be a 401
if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
//Unfortunately the redirect also clears the results of any authentication
//Try to manually authenticate the user...
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket),roles);
}
}
if (!context.Request.IsAuthenticated)
{
context.Response.Clear();
context.Response.StatusCode = 401;
}
}
}
这一切都按预期工作.
我应该删除这个问题吗?