Asp.net mvc 3 如何从自定义模型绑定器返回HTTP状态代码
我有一个自定义模型绑定器,它从MEF容器中提取接口的实现。其实施情况如下:Asp.net mvc 3 如何从自定义模型绑定器返回HTTP状态代码,asp.net-mvc-3,http-status-codes,defaultmodelbinder,imodelbinder,Asp.net Mvc 3,Http Status Codes,Defaultmodelbinder,Imodelbinder,我有一个自定义模型绑定器,它从MEF容器中提取接口的实现。其实施情况如下: public class PetViewModelBinder : DefaultModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var petId = bindingContext.ValueProvider.G
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);
}
}
公共类PetViewModelBinder:DefaultModelBinder
{
公共对象绑定模型(ControllerContext ControllerContext,ModelBindingContext bindingContext)
{
var petId=bindingContext.ValueProvider.GetValue(“id”);
var container=controllerContext.HttpContext.Application[mvcapapplication.PLUGINS]作为CompositionContainer;
懒惰的宠物=空;
尝试
{
pet=容器.GetExport(类型(IPet),petId);
var petVM=新模型。PetViewModel(pet);
bindingContext.ModelMetadata.Model=petVM;
返回base.BindModel(controllerContext、bindingContext);
}
捕获(例外)
{
投掷;
}
最后
{
集装箱出口(pet);
}
}
当MEF有一个petId导出时,这种方法非常有效……但当导出不存在时,它会返回http状态500(服务器错误)。错误消息混淆要求返回http状态403(禁止)
如何捕获错误、更改响应状态、不返回内容或重新路由操作以处理此情况?如果要返回特定的http状态代码,应通过控制器或操作筛选器执行此操作 一种方法是从模型绑定器中返回null,并在控制器中处理。这有点粗糙,因此您无法区分不同的错误 另一种方法是抛出特定的异常,并在(全局)错误处理中处理该异常。自定义的HandleError操作筛选器可以做到这一点:
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;
}
}
}
在控制器中,使用以下属性装饰动作:
[CustomHandleError( ExceptionType = typeof (NotAllowedException), View = "~/Views/Shared/Error.cshtml",
StatusCode = 403 )]
public ActionResult Index( FancyModel model )
{
return View( model );
}
最后,在您的模型绑定器中抛出NotAllowedException,这是您还需要定义的自定义异常类型
请注意,如果您在web.config文件中启用了自定义错误,则此操作仅适用于您的开发设置。谢谢!这无疑为我提供了一种不同的方式来看待此问题。全局错误处理在此项目上不起作用,但是,自定义错误处理程序应该可以工作。