【问题标题】:Web Api model validation result in MVC ViewMVC 视图中的 Web Api 模型验证结果
【发布时间】:2015-03-29 11:39:24
【问题描述】:

拥有这样的 Web Api 模型:

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

我的 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 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);
    }

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

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    您可以创建一个过滤器,将模型状态返回为 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

    【讨论】:

    • 但在我的情况下,我在客户端应用程序中有 ActionResult(你有 HttpResposeMessage)有什么区别吗?假设文件管理器是 Web Api 应用程序中的一个单独的类。我说的对吗?
    • 这不会影响客户端操作返回的内容。这应该在您的 api 上进行。然后来自 api 的响应将是 json 序列化模型状态,因此如果 api 上的验证失败,则客户端操作中的“响应”变量就是那个。
    猜你喜欢
    • 2010-11-18
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多