asp.net-mvc – 在ASP.NET MVC控制器结果中设置HTTP状态不呈现视
发布时间:2020-12-16 00:03:01 所属栏目:asp.Net 来源:网络整理
导读:我有一个自定义ActionResult用于返回某些HTTP错误,如NotFoundResult和ForbiddenResult,它们都派生自ViewResult. 如果在操作过程中没有在数据库中找到实体,我会将它们用于404的短路操作. 在这些结果对象中,我将HTTP状态设置为适当的数字.当我这样做时,这些Vie
|
我有一个自定义ActionResult用于返回某些HTTP错误,如NotFoundResult和ForbiddenResult,它们都派生自ViewResult.
如果在操作过程中没有在数据库中找到实体,我会将它们用于404的短路操作. 在这些结果对象中,我将HTTP状态设置为适当的数字.当我这样做时,这些ViewResults引用不会呈现的视图.我必须将状态保留为200 OK才能呈现我的视图. 如何在ASP.NET MVC 2.0中设置适当的状态并呈现视图? 解决方法
请允许我建议您替代错误处理: 首先创建一个错误控制器和相应的视图: public class ErrorController : Controller
{
public ActionResult General()
{
return View();
}
public ActionResult HttpError404()
{
return View();
}
public ActionResult HttpError500()
{
return View();
}
}
在Global.asax中定义Application_Error方法: protected void Application_Error(object sender,EventArgs e)
{
var exception = Server.GetLastError();
// TODO: Log the exception with your favorite logging framework
Response.Clear();
var httpException = exception as HttpException;
var routeData = new RouteData();
// Take the ErrorController
routeData.Values.Add("controller","error");
if (httpException == null)
{
// Use the General action for any unhandled error
routeData.Values.Add("action","general");
}
else
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values.Add("action","httpError404");
break;
case 500:
routeData.Values.Add("action","httpError500");
break;
default:
routeData.Values.Add("action","general");
break;
}
}
// Add the exception to route data so that the error controller
// could use it with RouteData.Values["error"]
routeData.Values.Add("error",exception);
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context),routeData));
}
最后抛出适当的例外: public class HomeController: Controller
{
public ActionResult Index(int id)
{
var model = _repository.GetModel(id);
if (model == null)
{
throw new HttpException(404,"Model not found with id = " + id);
}
return View(model);
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 在jQuery中捕获异常
- asp.net表单身份验证重定向问题
- asp.net – 如何在IIS 7.5上调试经典的asp页面Visual Studi
- asp.net – HTTPS停止使用IIS express
- Mvc分页组件MvcSimplePager代码重构及使用
- ASP.net图表控件:隐藏除数据点之外的所有行(轴等)
- asp.net – 如何集成ASP .Net Model View Presenter(MVP)模
- asp.net-mvc-3 – MVC3正确的方式来改变每个请求的文化
- asp.net-mvc – 在ASP.NET MVC中调用Session_End()的时间是
- ASP.NET MVC问题配置表单认证部分
推荐文章
站长推荐
- asp.net-mvc – MVC 3 Url Helper提供不正确的UR
- asp.net-mvc-4 – WepApi控制器是否应该返回view
- asp.net-web-api – 返回Web API中的错误
- asp.net – 我有多个用户,我可以锁定网页,以便一
- asp.net-mvc – ASP.NET MVC:通过两个控制器操作
- asp.net-mvc-4 – 当连接connecttring configSou
- asp.net – 什么原因导致“无法注销UpdatePanel”
- 在asp.net mvc中如何使用usercontrols来显示“岛
- asp.net-mvc – Nhibernate / MVC:在View中处理
- asp.net-mvc – Asp.net MVC和普通的html页面
热点阅读
