2015-12-23 39 views
0

我想學習WebApi並得到以下錯誤。WebApi發佈和路由在同一類

錯誤CS1929「HttpRequestBase」不包含關於「CreateResponse」和最好的擴展方法過載的定義「HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage,HttpStatusCode,PilotModel)」需要類型

的「HttpRequestMessage」的接收器我想從我的Post方法返回一個HTTPResponseMessage,並且需要從WebApi繼承,但不能,因爲我從Controller繼承。我的班級設置有誤嗎?我不應該混合路由和WebApi呼叫?我該怎麼做?

public class RegistrationController : Controller 
{ 
    private RegistrationService registrationService; 

    public RegistrationController() 
    { 
     this.registrationService = new RegistrationService(); 
    } 

    public ActionResult Index() 
    { 
     ViewBag.Title = "Registration Page"; 

     return View(); 
    } 

    public HttpResponseMessage Post(PilotModel pilot) 
    { 
     this.registrationService.RegisterPilot(pilot); 

     var response = Request.CreateResponse<PilotModel>(HttpStatusCode.Created, pilot); 

     return response; 
    } 
} 
+1

對於從'ApiController'繼承的API調用,您應該有一個單獨的控制器類。在同一個類中混合控制器操作和API控制器操作將不起作用(還)。 –

+0

因此,我可以在一個API控制器中添加Post(PilotModel pilot)並返回一個HttpResponseMessage?那是我應該做的嗎? – Wannabe

回答

2

您將需要兩個不同的控制器類。

namespace MyApp.Controllers 
{ 
    public class RegistrationController : Controller 
    { 
     private RegistrationService registrationService; 

     public RegistrationController() 
     { 
      this.registrationService = new RegistrationService(); 
     } 

     public ActionResult Index() 
     { 
      ViewBag.Title = "Registration Page"; 

      return View(); 
     } 
    } 
} 

你也可能需要添加[FromBody]來區分的pilot是從表格數據,而不是一個URL參數(假設你使用的是形式或在郵件正文中另有發送數據)。

namespace MyApp.ApiControllers 
{ 
    public class RegistrationController : ApiController 
    { 
     private RegistrationService registrationService; 

     public RegistrationController() 
     { 
      this.registrationService = new RegistrationService(); 
     } 

     public HttpResponseMessage Post([FromBody]PilotModel pilot) 
     { 
      this.registrationService.RegisterPilot(pilot); 

      var response = Request.CreateResponse<PilotModel>(HttpStatusCode.Created, pilot); 

      return response; 
     } 
    } 
} 
+0

感謝您的分解! – Wannabe