我正在使用REST for ASP.NET MVC框架(MVC 2)实现Web API。我想封装这段代码,理想情况是在ActionFilterAttribute(?)中,这样我就可以装饰总是执行相同逻辑的特定操作:
if (!ModelState.IsValid) {
return View(
new GenericResultModel(){ HasError=True, ErrorMessage="Model is invalid."});
}
我真的不想将这个样板代码复制并粘贴到我需要执行此操作的每个控制器操作中。
在这个Web API场景中,我需要能够执行这样的操作,以便调用者可以以JSON或POX形式返回结果并查看是否存在错误。在ASPX视图中,显然我不需要这样的东西,因为验证控件会负责通知用户问题。但我没有ASPX视图 - 我只返回从我的模型序列化的JSON或POX数据。
我已经在ActionFilter中开始使用此代码,但我不确定下一步该做什么(或者它是否是正确的起点):
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool result = filterContext.Controller.ViewData.ModelState.IsValid;
if (!result)
{
GenericResultModel m = new GenericResultModel() { HasError = true };
// return View(m)
// ?????
}
base.OnActionExecuting(filterContext);
}
我如何做到这一点?
答案 0 :(得分:4)
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Notice that the controller action hasn't been called yet, so
// don't expect ModelState.IsValid=false here if you have
// ModelState.AddModelError inside your controller action
// (you shouldn't be doing validation in your controller action anyway)
bool result = filterContext.Controller.ViewData.ModelState.IsValid;
if (!result)
{
// the model that resulted from model binding is not valid
// => prepare a ViewResult using the model to return
var result = new ViewResult();
result.ViewData.Model = new GenericResultModel() { HasError = true };
filterContext.Result = result;
}
else
{
// call the action method only if the model is valid after binding
base.OnActionExecuting(filterContext);
}
}