我有一个自定义模型绑定(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/