我正在尝试学习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;
}
}
答案 0 :(得分: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;
}
}
}