我正在使用温莎城堡工厂根据请求 url 实例化一个对象。
类似于:
public FooViewModel Get()
{
if (HttpContext.Current == null)
{
return new FooViewModel();
}
var currentContext = new HttpContextWrapper(HttpContext.Current);
// resolve actual view model.
在某些情况下,我实际上想抛出 404 并停止请求,目前如:
throw new HttpException(404, "HTTP/1.1 404 Not Found");
currentContext.Response.End();
但是请求并没有结束,它仍然点击 Action 并尝试解析 View ?
我的 Controller 看起来像这样:
public class HomeController : Controller
{
public FooViewModel Foo { get; set; }
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
我是不是想错了?或者有什么方法可以实现这一点?
我正在考虑的替代方案是检查 Foo 属性状态的操作属性?
最佳答案
我认为使用 Action 过滤器的方法可以实现您想要的:
public class RequiresModelAttribute : ActionFilterAttribute
{
private readonly string _modelName;
public RequiresModelAttribute(string modelName)
{
_modelName = modelName;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var property = filterContext.Controller.GetType().GetProperty(_modelName);
var model = property.GetValue(filterContext.Controller);
if (model == null)
{
filterContext.Result = new HttpStatusCodeResult(404);
}
}
}
然后,在您的 Controller 上您可以:
public class HomeController : Controller
{
public FooViewModel Foo { get; set; }
[RequiresModel("Foo")]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
}
编辑:也许使用全局过滤器来处理任何抛出的 HttpExceptions?
public class HonorHttpExceptionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var httpException = filterContext.HttpContext.AllErrors.FirstOrDefault(x => x is HttpException) as HttpException;
if (httpException != null)
{
filterContext.Result = new HttpStatusCodeResult(httpException.GetHttpCode());
}
}
}
然后在 Global.asax 中:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new HonorHttpExceptionAttribute());
}
关于c# - 如何结束响应并发回 HTTP 代码 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379418/