gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:06:24 28 4
gpt4 key购买 nike

我正在使用温莎城堡工厂根据请求 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com