2017-08-24 26 views
0

我有一個簡單的登錄表單,它在LogIn按鈕上單擊,執行對ActionResult LogIn(LogInRequest request)的的調用,返回AccountController,返回JsonResult。我有CustomHandleErrorAtributeHandleErrorAttribute繼承,並重定向到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並且不執行重定向。你知道如何處理這個?

回答

1

因爲你確實得到一個異常,所以ajax調用本身失敗,這就是爲什麼你會得到警報,但是你不能重定向到ajax調用服務器端的另一個頁面。相反,您可以將重定向放入ajax調用的失敗塊中。就像....

error: function(){ 
    window.location = <put error page url here> 
    alert('error'); 
} 
+0

謝謝你,我會將你的回答標記爲答案。對於那些在這方面掙扎的人,我在這裏用CustomAjaxHandleErrorAtribute發現了可能的解決方案,它返回Json結果給ajax調用的錯誤函數: https://stackoverflow.com/questions/9298466/can-i-return-custom-error-從-jsonresult到jQuery的Ajax的誤差的方法 – Gamaboy