我有一個要求,當用戶的會話過期並重定向到登錄頁面時顯示警報。 其實我已經創建了一個應用在控制器上的動作過濾器,它會在會話過期時檢查 ,如果它重定向到登錄頁面,則它會讓動作成功完成 。使用ActionFilters和會話處理Asp.net MVC頁面中的安全性
它工作正常,但當我發出ajax請求時出現問題。 對於一個實例,我在我的視圖中有ajax.beginform,並且我已經完成了在該acion 方法上的代碼保存。現在,假設用戶在會話過期之前提交了表單, 在保存方法運行之前,我的actionFilter調用了,因爲我已經在 控制器上設置了它。所以,從那裏說,重定向到登錄頁面。 但我從控制器返回Json,它不重定向。
我應該如何實現這些東西?
我的代碼是::::::::::::
對於每一個控制器,我的行爲過濾器以同樣的方式定義,我只是要定義僅適用於一個控制器因此,假設如下是我的控制器。
[CheckSessions]
public class MyController : Controller
{
public ActionResult Add(Model model)
{
Insert code and returns
return Json(new { Msg = Message});
}
}
Action Filter is here
public class CheckSessions: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["LoginSession"] == null && HttpContext.Current.Session["LoginSession"] == null)
{
HttpContext.Current.Response.Redirect("/LoginController/Login");
}
}
}
In View Page:::
@using (Ajax.BeginForm("Add", "MyController ", new AjaxOptions { OnSuccess = "MessageConfirmation" }))
{
Content goes here
}
<script>
Getting Response
function MessageConfirmation(Json) {
alert(Json.StatusCode);
if(Json.StatusCode==404)
{
redirect to login
}
}
</script>
但我將如何發送狀態,由json?請給出你的建議。 – Sweetie
@Sweetie,只要設置HttpContext.Current.Response.ContentType =「application/json」'如果它是一個JSON請求 –
@Sweetie,則不需要設置內容類型,因爲您正在處理請求狀態,這將可用於所有的jQuery ajax請求,包括GET,POST,JSONP等 –