我在做错误处理(403,404,500)。 我做了ErrorController
和Views
:
public class ErrorController : Controller
{
// GET: Error
public ActionResult General(Exception exception)
{
return View("Exception", exception);
}
public ActionResult Http404()
{
return View();
}
public ActionResult Http403()
{
return View();
}
}
然后我写了下面的代码在Global.asax.cs
:
protected void Application_Error()
{
var exception = Server.GetLastError();
log.Error(exception);
Response.Clear();
var httpException = exception as HttpException;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values.Add("action", "Http403");
break;
case 404:
routeData.Values.Add("action", "Http404");
break;
default:
routeData.Values.Add("action", "Error");
break;
}
}
else
{
routeData.Values.Add("action", "General");
routeData.Values.Add("exception", exception);
}
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
IController errorsController = new ErrorController();
errorsController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
它的工作原理,当URL与控制器的名称(例如: http://localhost:62693/News/123
),然后我得到了错误的404视图。
但是,当我在它或无效的控制器名称发送URL无控制器的名称(例如: http://localhost:62693/123
或http://localhost:62693/new/k
),我只拿到了HTML
错误的404视图的代码。
我怎样才能得到错误的观点404与任何网址吗?