asp.net-mvc-3 - 如何从 Custom Model Binder 返回 HTTP 状态代码

标签 asp.net-mvc-3 http-status-codes defaultmodelbinder imodelbinder

我有一个自定义模型绑定(bind)器,它从 MEF 容器中提取接口(interface)的实现。它的实现如下:

public class PetViewModelBinder : DefaultModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var petId = bindingContext.ValueProvider.GetValue("id");
        var container = controllerContext.HttpContext.Application[MvcApplication.PLUGINS] as CompositionContainer;
        Lazy<IPet, IPetMetadata> pet = null;
        try
        {
            pet = container.GetExport(typeof(IPet), petId);
            var petVM = new Models.PetViewModel(pet);
            bindingContext.ModelMetadata.Model = petVM;

            return base.BindModel(controllerContext, bindingContext);
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            container.ReleaseExport(pet);
        }

    }

当 MEF 具有 petId 的导出时,这非常有效...但是当导出不存在时返回 http 状态 500(服务器错误)。错误消息混淆要求规定应返回 http 状态 403(禁止)。

如何捕获错误、更改响应状态、不返回内容或重新路由 Action 来处理这种情况?

最佳答案

如果你想返回一个特定的 http 状态代码,你应该从 Controller 或操作过滤器中返回。

执行此操作的一种方法是从您的模型绑定(bind)器返回 null 并在您的 Controller 中处理它。但是,这有点粗糙,因此您将无法区分不同的错误。

另一种方法是抛出一个特定的异常并在您的(全局)错误处理中处理它。自定义的 HandleError Action 过滤器可以做到这一点:

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
  public int StatusCode { get; set; }

  public override void OnException( ExceptionContext filterContext )
  {
     base.OnException( filterContext );
     if ( StatusCode > 0 )
     {
        filterContext.HttpContext.Response.StatusCode = StatusCode;
     }
  }
}

在你的 Controller 中,用这个属性装饰 Action :

[CustomHandleError( ExceptionType = typeof (NotAllowedException), View = "~/Views/Shared/Error.cshtml",
     StatusCode = 403 )]
public ActionResult Index( FancyModel model )
{
   return View( model );
}

最后,在您的模型绑定(bind)器中抛出 NotAllowedException,这是您还需要定义的自定义异常类型。

请注意,如果您在 web.config 文件中启用了自定义错误,这仅适用于您的开发设置。

关于asp.net-mvc-3 - 如何从 Custom Model Binder 返回 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184802/

相关文章:

c# - 从局部 View 将数据传递到局部 View 的最简单方法

asp.net-mvc - 改变 : * incorrectly added to http header response (asp. 净 mvc3)

ruby-on-rails - 在 Rails 中返回特定的 http 状态码

jquery - jQuery AJAX XMLHTTPRequest在错误状态下没有有用的信息

java - 检查 url 是否有效时出现错误

asp.net-mvc - 在强类型 View 中格式化可为空的 DateTime 字段

asp.net-mvc-2 - 派生对象列表的 MVC2 Modelbinder

c# - 如何在 Html.Editor 中直接加载 Object additionalViewData 的值?

asp.net-mvc-2 - 使用抽象类的 Asp.Net MVC 2 DefaultModelBinder 错误

asp.net - 为 favicon 添加忽略路由后如何修复 "File does not exist"错误