WebApi Post和Routing在同一类中
本文关键字:一类 Post Routing WebApi | 更新日期: 2023-09-27 18:28:04
我正在尝试学习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;
}
}
您将需要两个不同的控制器类。
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;
}
}
}