简体   繁体   English

如何结束响应并发回HTTP代码404?

[英]How can I end a response and send HTTP code 404 back?

I am using a castle windsor factory to instantiate an object based on the request url. 我正在使用城堡windsor工厂根据请求网址实例化一个对象。

Something like: 就像是:

    public FooViewModel Get()
    {
        if (HttpContext.Current == null)
        {
            return new FooViewModel();
        }

        var currentContext = new HttpContextWrapper(HttpContext.Current);

        // resolve actual view model.

In some cases, I actually want to throw a 404 and stop the request, currently like: 在某些情况下,我实际上想要抛出404并停止请求,目前如下:

        throw new HttpException(404, "HTTP/1.1 404 Not Found");
        currentContext.Response.End();

However the request doesn't end and it still hits the Action and tries to resolve the view? 但是请求没有结束,它仍然命中Action并尝试解析视图?

My Controller would look something like this: 我的控制器看起来像这样:

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();
    }

Am I thinking about this all wrong? 我觉得这一切都错了吗? Or is there a way I can achieve this? 或者有没有办法实现这一目标?

The alternative I was thinking of is an attribute on the action to check the state of the Foo property? 我想到的另一种选择是检查Foo属性状态的动作属性?

I think the approach of using an action filter could achieve what you are wanting: 我认为使用动作过滤器的方法可以达到你想要的效果:

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);
        }
    }
}

Then, on your controller you could do: 然后,在您的控制器上,您可以:

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();
    }
}

Edit: Perhaps using a global filter to honor any thrown HttpExceptions? 编辑:也许使用全局过滤器来兑现任何抛出的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());
        }
    }
}

Then in Global.asax: 然后在Global.asax中:

  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
      filters.Add(new HandleErrorAttribute());
      filters.Add(new HonorHttpExceptionAttribute());
  }

Another option is overriding OnException on Controller. 另一个选项是覆盖Controller上的OnException。

 public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        Get();
        return View();
    }

    public int Get()
    {
        throw new HttpException(404, "HTTP/1.1 404 Not Found");
        // we don't need end the response here, we need go to result step
        // currentContext.Response.End();

    }

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
        if (filterContext.Exception is HttpException)
        {
            filterContext.Result = this.HttpNotFound(filterContext.Exception.Message);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM