从ASP.NET mvc3中的模型重定向

时间:2012-05-30 18:03:36

标签: asp.net asp.net-mvc-3 redirect model

道歉,如果这是一个愚蠢的问题,但我只是想知道在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
        }
    }

我知道在这个特定的例子中,错误实际上并没出现在模型中,所以我只能从控制器重定向。但是我希望能够调用一个能够记录然后重定向的函数,因为这对于可能发生的许多其他错误是必要的。

我可能会以完全错误的方式解决这个问题,在这种情况下,我当然愿意接受改变。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

我个人使用MVC框架提供的全局exception filter来写入错误日志。我还通过Web配置使用默认重定向到错误视图:

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

这个模型当然有可能存在的缺点,但它涵盖了我到目前为止遇到的大多数例外情况。

答案 1 :(得分:1)

您可以从HttpContext访问响应。

HttpContext.Current.Response

答案 2 :(得分:0)

很简单,

您需要将结果(ActionResult)分配给filterContext.Result

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

或重定向

filterContext.Result = Redirect(url);

filterContext.Result = RedirectToAction("actionname");