我有一個簡單的登錄表單,它在LogIn按鈕上單擊,執行對ActionResult LogIn(LogInRequest request)
的的調用,返回AccountController
,返回JsonResult
。我有CustomHandleErrorAtribute
從HandleErrorAttribute
繼承,並重定向到CustomErrorPage.cshtml
。 Somwhere在ActionResult異常中被拋出,應該由CustomHandleErrorAtribute
來處理,並被處理。然後執行CustomErrorPage操作,但它實際上並沒有返回視圖。它保持在相同的LogInPage上。由於Ajax調用而未執行重定向
在AccountsController我的登錄操作的登錄按鈕
[AllowAnonymous]
[HttpPost]
[CustomAttributes.CustomHandleError]
public ActionResult Login(LogInRequest request)
{
StandartResponse finalResult = new StandartResponse();
//some code that trows exception
return new JsonResult() { Data = finalResult.Result};
}
我的Ajax調用點擊:
function LogInUser(s, e) {
var example = { username: UserName.GetValue(), password: Password.GetValue() };
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: "POST",
url: "/Account/LogIn",
data: JSON.stringify({ request: example }),
success: function (data) {
jQuery.ajaxSettings.traditional = true;
if (data.Status == InfoType.Success) {
alert('success');
var url = "/Home/Index";
window.location.href = url;
}
else {
alert('here');
var result = JSON.stringify(data.Infoes);
popUpErrorMessagePartial.PerformCallback({ message: result });
popUpErrorMessagePartial.Show();
}
},
error: function(){
alert('error');
}
});
}
CustomHandleErrorAttribute:
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{ "action", "ErrorUnauthorised" },
{ "controller", "CustomErrorPages" },
{ "Area", String.Empty }
});
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
}
調試CustomErrorPage的行動之後被執行,但然後執行ajax調用中的錯誤,顯示allert並且不執行重定向。你知道如何處理這個?
謝謝你,我會將你的回答標記爲答案。對於那些在這方面掙扎的人,我在這裏用CustomAjaxHandleErrorAtribute發現了可能的解決方案,它返回Json結果給ajax調用的錯誤函數: https://stackoverflow.com/questions/9298466/can-i-return-custom-error-從-jsonresult到jQuery的Ajax的誤差的方法 – Gamaboy