Asp.net

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

  • January 15, 2019

我們有一個完全在 AngularJS 上執行的網站,其 ASP.NET Web API 後端具有以下配置: - 在 Angular 上啟用了 HTML5 路由,並且在 web.config 中有一個重寫規則將所有流量定向到 index.html -未安裝 MVC(僅 razor 頁面)- 使用表單身份驗證和相關 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>

如果您使用的是 ASP.NET 4.5。您可以禁用表單身份驗證重定向 HttpResponse.SuppressFormsAuthenticationRedirect 屬性。

在 Global.asax 中:

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

總之,我把它放在 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;
   }
}

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";
}

因此對於每個 ajax 請求表單,auth 將不再被重定向。這是我找到的最好的解決方案。

並且可以選擇將其放入客戶端程式碼中,以便在收到 401 錯誤答案後重新載入頁面。

$(document).ajaxError(function (xhr, props) {
   if (props.status === 401) {
       location.reload();
   }
});

引用自:https://stackoverflow.com/questions/18519446