[英]Ajax request after MVC authentication timeout/session cookie deleted
用戶超時或刪除會話cookie cookie時,使用MVC 5身份驗證,可以將用戶重定向到登錄頁面。
這在整個頁面加載時都可以正常工作,但是對於我的Ajax來說,這會打斷客戶端。 重定向在身份驗證頁面顯示時起作用,但是沒有響應(在標准加載輪之后)。
我很確定這是某種JS問題。
JS:
$(function () {
$('#dealSearchForm').on("submit", function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$('#dealSearchForm').html(data);
},
complete: function (data) {
$('#searchResults').show();
}
});
});
});
主視圖:
@{Html.RenderPartial("_DealSearch");}
<script src="@Url.Content("~/Scripts/DealSearch.js")"></script>
<script>
$(document).ready(function () {
@if (Model.Deals.Count > 0) {
@Html.Raw("$('#searchResults').show();");
}
});
</script>
部分視圖:
@using (Html.BeginForm("DealSearch", DealManagement, FormMethod.Post, new { @id = "dealSearchForm" }))
{
/* Search filters etc */
<div class="col-xs-7">
<button id="button-search" class="btn btn-primary pull-right" type="submit" data-loading-text="Please wait...">Search</button>
</div>
<div id="searchResults">
/* Grid with results */
</div>
控制器:
public virtual ActionResult Index()
{
var model = new DealSearchModel();
return this.View(model);
}
public virtual ActionResult DealSearch(DealSearchModel model)
{
// Get deals from service, uses search criteria
model.Deals = GetDeals(model);
// Return the view
return PartialView(MVC.DealManagement.Views._DealSearch, model);
}
客戶端出現錯誤:
如果有人有任何想法,將不勝感激!
您必須覆蓋默認行為-我假設您的問題是,當用戶點擊需要授權的操作並且當前會話已過期時,AJAX響應不再有效。
您沒有提供方法的授權方式,而是考慮創建自定義授權屬性:
public class CustomAuthorizationAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Check whether it is an AJAX or standard request
}
}
如何檢查是否是AJAX請求,您可以在這里找到。 而不是重定向,您應該返回403未經授權的結果並在您的AJAX調用中進行處理。
使用基於Kamos答案的方法,我使用以下方法解決了這個問題:
自定義屬性
public class AuthoriseAjaxAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new RedirectResult("~/Error/AjaxUnauthorized");
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
/ Error / AjaxUnauthorized視圖
@{
Layout = ""; // Result of an ajax call
}
// Refresh the page, resulting in MVC default login/redirection
<script>
$(document).ready(function($) {
location.reload(true);
});
</script>
// Only here for if Javascript is off
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12">
Authorisation timeout.
</div>
</div>
</div>
<div class="panel-body black-text">
Please refresh the page and log back in.
</div>
</div>
對於用戶而言,這使得Ajax調用以相同的方式響應超時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.