开发者

potentially dangerous request redirect to error page

I use request validation on asp.net mvc 2 on .NET 4, and whenever I post htmlcode to my controller action. that is good. But I see now my yellow screen of death. Instead of that I want to redirect the user to my custom error page for this. What do I need to开发者_Python百科 change in my web.config to redirect to

 ~/Home/InvalidInput 

for example.


You want to add that info to the customErrors element in the web.config. This element is defined under the system.web tag.

<customErrors mode="RemoteOnly" defaultRedirect="/Home/InvalidInput " />

Also, you will need to define a route to handle this redirect since that is nothing more than a URL. Just specify an route and an action in your HomeController that will return the InvalidInput view when this route is hit.


Setup a custom base controller that HomeController (and whatever others you have) inherits from. Then you can setup exception handling in the base controller:

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnException(filterContext);
            return;
        }

        filterContext.ExceptionHandled = true;

        if (filterContext.Exception is HttpException)
        {
            var statusCode = ((HttpException) filterContext.Exception).GetHttpCode();
            Response.StatusCode = statusCode;

            if (statusCode == (int) HttpStatusCode.NotFound)
            {
                filterContext.Result = View(ErrorController.Actions.NotFound);
            }
            else
            {
                filterContext.Result = View(ErrorController.Actions.InternalServerError);
            }
        }
        else
        {
            Response.StatusCode = (int) HttpStatusCode.InternalServerError;
            filterContext.Result = View(ErrorController.Actions.InternalServerError);
        }

        base.OnException(filterContext);
    }

Of course you will need your own ErrorController and error views as well.

The benefit in this is that a) you have greater control over how exceptions are handled, b) you can set the appropriate HTTP status code, and c) you can unit test your error handler.

The defaultRedirect property of customErrors will work as well as a more basic approach, however you cannot unit test the behavior, and users are then exposed to your error routes rather than staying on the current URI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜