2012-05-30 43 views
0

道歉,如果這是一個愚蠢的問題,但我只是想知道最好的方式去重定向到一個錯誤頁面當一個模型中發生錯誤在asp.net mvc3 。從ASP.NET中的模型重定向mvc3

總之,我有一個ApplicationController中,所有的控制器繼承,其中,在「OnActionExecuting」功能,檢查是否用戶使用Internet Explorer。

如果是這樣,我把我的誤差模型的函數(我有,因爲我要記錄的錯誤在數據庫中),則應該將用戶重定向到告訴下載Chrome瀏覽器的錯誤頁面。

的ApplicationController

public class ApplicationController : Controller 
{ 
    public string BASE_URL { get; set; } 

    public ApplicationController() {} 

    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 

     BASE_URL = Url.Content("~/"); 

     ErrorModel err = new ErrorModel(); 

     String userAgent; 
     userAgent = Request.UserAgent; 
     if (userAgent.IndexOf("MSIE") > -1) { 
      err.cause("browser", "redirect", "some other info"); 
     }   
    } 
} 

ErrorModel

public void cause(string _errCode, string strAction, string _otherInfo = "") { 

     this.error_code = _errCode; 
     this.error_otherInfo = _otherInfo; 

     try { 
      this.error_message = dctErrors[_errCode.ToLower()]; 
     } catch (KeyNotFoundException) { 
      this.error_message = "Message not found."; 
     } 

     StackTrace sT = new StackTrace(true); 
     String[] filePathParts = sT.GetFrame(1).GetFileName().Split('\\'); 

     this.error_filename = filePathParts.Last(); 
     this.error_lineNo = sT.GetFrame(1).GetFileLineNumber(); 

     this.error_function = sT.GetFrame(1).GetMethod().ReflectedType.FullName; 

     this.error_date = DateTime.Now; 
     this.error_uid = 0; //temporary 

     if (strAction == "redirect") { 
     //this is what I would like to do - but the "response" object does not 
     //exist in the context of the model 
      Response.Redirect("Error/" + _errCode);     
     } else if (strAction == "inpage") { 

     } else { 
      //do nothing 
     } 
    } 

我知道在這個特殊的例子,其誤差不實際發生的模型,所以我可以從控制器重定向。但是我希望能夠調用一個函數,如果可能的話,它會記錄並重定向,因爲這對於可能發生的許多其他錯誤是必需的。

我可能會對此完全錯誤的方式,在這種情況下,我當然是開放的變化。謝謝您的幫助!

+2

業務邏輯不應該在你的模型。將它移到你的控制器。 – Jesse

+4

業務邏輯不應該在控制器中! – c0deNinja

回答

1

你可以訪問來自HttpContext的響應。

HttpContext.Current.Response 
1

我個人使用全球exception filter,由MVC框架提供,寫入錯誤日誌。我還使用了默認重定向到通過網絡配置錯誤觀點:

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/"> 

有,當然,可能的缺點,這種模式,但它涵蓋了大部分到目前爲止,我所遇到的異常。

0

ITS簡單得多,

您需要分配結果(ActionResult的),以filterContext.Result

filterContext.Result = View("ErrorView", errorModel); 

或重定向

filterContext.Result = Redirect(url); 

filterContext.Result = RedirectToAction("actionname");