如何将模型传递给WebApi控制器?

时间:2017-01-29 07:29:05

标签: c# asp.net-mvc design-patterns asp.net-web-api dependency-injection

我需要编写WebApi控制器。任务是从exisitng普通mvc控制器迁移到WebApi控制器。

在这个项目中,几乎所有的编程之美都被用作: -

  • 设计模式 - 存储库+ UOW,工厂+ nUnit
  • 依赖注入
  • SOLID

这是MyApp.Domain图层中的模型

public class Customer
{
   //please note that we are using Repository pattern & so no Data Annotations like Required, Key are not used here. 
   public int CustomerID { get; set;}

   public string CustomerName { get; set;}

   public string EmailAddress { get; set;}
   // & so on
}

MyApp.UI图层中,存在用于验证的ViewModel&然后将模型传递给Service层。这就是我的MVC控制器的样子

  public class CustomerVM
  {
     [Required]
     public int CustomerID { get; set;}  // & so on the other properties.

  }


  public ActionResult Registration(Customer VM)
  {
         if(Modelstate.IsValid)
         {
            //call service layer 
         }
         else
         {

         }
  }

现在我的当务之急是将此控制器迁移到WebApi控制器。 从此以后,我创建了一个单独的项目MyApp.WebApi

现在我的疑问是我应该如何将模型传递给这个WebApi控制器。

我正在考虑将ViewModel从UI层分离出来 将项目设置为MyApp.ViewModels并将所有视图模型放在此图层中 &安培;在UI图层中引用dll& WebApi层。

 public string POST([FromBody]CustomerVM customer)
 {
    if(Modelstate.IsValid)
    {
        //call the other service layer which will take care of DB handling
       return "Success";
    }
    else
    {
       return "Error";
    }   
 }

这是正确的做法吗?还有其他正确的方法吗?

2 个答案:

答案 0 :(得分:1)

在RESTful API中,您称之为视图模型的是 DTO ,或者在Web API俚语中,它们是模型

您知道ASP.NET MVC和WebAPI都具有相似的体系结构,并且在ASP.NET MVC Core中,它们已合并为单个编程模型。也就是说,ASP.NET MVC中有效的内容在WebAPI中也是有效的。

检查您是否不需要[FromBody]属性。 模型会自动绑定到身体。

答案 1 :(得分:1)

您也可以使用IHttpActionResult而不是字符串并抛出实际错误。

public IHttpActionResult  POST([FromBody] CustomerVM customer)
 {
   if (!ModelState.IsValid) {
        return BadRequest(ModelState);
    }
     return Ok("success");

 }