Asp.net mvc MVC视图中的Web Api模型验证结果

Asp.net mvc MVC视图中的Web Api模型验证结果,asp.net-mvc,asp.net-web-api,Asp.net Mvc,Asp.net Web Api,具有如下Web Api模型: public class Meel { public int Id { get; set; } [Required] public string VaskNr { get; set; } } public ActionResult Create(MeelModel model) { HttpClient client = new HttpClient(); client.BaseAddress =

具有如下Web Api模型:

 public class Meel
{
    public int Id { get; set; }
    [Required]
    public string VaskNr { get; set; }
}
 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);
    }
我的Post API控制器是

  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 class Meel
{
    public int Id { get; set; }
    [Required]
    public string VaskNr { get; set; }
}
 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);
    }
公共行动结果创建(MeelModel模型)
{
HttpClient=新的HttpClient();
client.BaseAddress=新Uri(“http://localhost:3806/");
var response=client.PostAsJsonAsync(“api/meels”,model.)。结果;
返回视图(模型);
}

我的问题是如何将验证结果返回给我的视图,即“需要VaskNr”。我的视图是由MVC模板生成的。当只使用没有Web API的MVC应用程序时,将错误返回到视图是没有问题的。

您只需创建一个过滤器,将modelstate返回为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)
{
    // ...
}

请参阅:

但在我的例子中,客户端应用程序中有ActionResult(您有HttpResposeMessage),有什么区别吗?假设文件管理器是web Api应用程序中的一个独立类。我说的对吗?这不会影响客户端操作返回的内容。这应该放在你的api上。然后来自api的响应将是json序列化模型状态,因此,如果api上的验证失败,则客户端操作中的“response”变量将为该状态。