我可以使用2种不同数据类型的post方法: -
[HttpPost]
public HttpResponseMessage Post([StringBody]string data)
{
// Logic
}
[HttpPost]
public HttpResponseMessage Post(Requirements objRequirement)
{
//Logic
}
我在邮递员中遇到错误: -
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Multiple actions were found that match the request:
System.Net.Http.HttpResponseMessage Post(Newtonsoft.Json.Linq.JObject) on type ATL.Trebuchet.RestApi.Controllers.ValuesController
System.Net.Http.HttpResponseMessage Post(ATL.Trebuchet.RestApi.Models.Requirements) on type ATL.Trebuchet.RestApi.Controllers.ValuesController</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace> at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)</StackTrace>
</Error>
请帮助如何使用不同类型的参数具有相同的Post方法
我发送的数据为Text (text/plain)
编辑1:
答案 0 :(得分:3)
如果要在同一个控制器中使用多个post方法,则需要将它们映射到不同的路径或操作
Web api 1
将路由添加到WebApiConfig,您可以查看此answer以获取详细信息,但重要的是指定默认路由api / controller / id仅接受整数。否则,操作将被视为字符串ID。
routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}"
);
然后在控制器中指定方法的ontop动作
public class DataController : ApiController
{
[HttpPost]
[ActionName("post1")]
public HttpResponseMessage Post([StringBody]string data)
{
// Logic
}
[HttpPost]
[ActionName("post2")]
public HttpResponseMessage Post(Requirements objRequirement)
{
//Logic
}
}
Web api 2
您可以在此处使用属性路由
[RoutePrefix("api/data")]
public class DataController : ApiController
{
[HttpPost]
[Route("post1")]
public HttpResponseMessage Post([StringBody]string data)
{
// Logic
}
[HttpPost]
[Route("post2")]
public HttpResponseMessage Post(Requirements objRequirement)
{
//Logic
}
}
第一个post方法将被称为api / data / post1和第二个api / data / post2