[英]Redirect users to logon page only if not authonticated in asp.net MVC
[英]ASP.NET logon redirect without explicit logon
帶有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並且沒有人做任何奇怪的事情。 我還檢查了登錄頁面URL的查詢(通過GetRedirectUrl()
),但仍然沒有。
有沒有人有什么想法做autoredirect?
我唯一的猜測是AuthenticateRequest
方法不是這里Request的生命周期的結束。 其結果是,該Response
被最終返回給用戶是重定向響應。 在捕獲並修改AJAX Response
之后,應該嘗試顯式結束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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.