MVC 视图中的 Web Api 模型验证结果

Web Api model validation result in MVC View

拥有这样的 Web Api 模型:

 public class Meel
{
    public int Id { get; set; }
    [Required]
    public string VaskNr { get; set; }
}

我的 API Post 控制器是

  public IHttpActionResult PostMeel(Meel meel)
    {
        if (!ModelState.IsValid)
        {

            return BadRequest(ModelState);
        }

        db.Meels.Add(meel);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = meel.Id }, meel);
    }

我从这样的 MVC 客户端调用我的 Web Api:

 public ActionResult Create(MeelModel model)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:3806/");
        var response = client.PostAsJsonAsync<MeelModel>("api/meels", model).Result;
        return View(model);
    }

我的问题是如何 return 验证结果,即 "VaskNr is required" 到我的视图。我的视图是由 MVC 模板生成的。当仅使用不带 Web 的 MVC 应用程序时 API return 视图错误没有问题。

您可以创建一个 returns 模型状态为 json

的过滤器

过滤器:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

为所有控制器设置过滤器:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ValidateModelAttribute());

        // ...
    }
}

为一个控制器设置过滤器:

[ValidateModel]
public HttpResponseMessage Post(Product product)
{
    // ...
}

参见:http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api