我的动作有不同的类型参数。
public class MyController : ApiController
{
[HttpPost]
public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
{
return new UpdateFeatureResponse { IsSuccess = true };
}
[HttpPost]
public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
{
return new DeleteFeatureResponse{ IsSuccess = true };
}
}
我的请求类型是这样的:
public class UpdateFeatureResuest
{
public int Id { get; set; }
public string Feature { get; set; }
}
public class UpdateFeatureResponse
{
public bool IsSuccess { get; set; }
}
public class DeleteFeatureRequest
{
public int Id { get; set; }
}
public class DeleteFeatureResponse
{
public bool IsSuccess { get; set; }
}
路线在这里:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
当我通过fiddler发送请求(http://localhost:52285/api/My/UpdateFeature
)时,它返回 HTTP / 1.1 500内部服务器错误
错误信息是:
{“message”:“发生错误。”,“exceptionMessage”:“在WebGUI.Controllers类型上找到与请求匹配的多个操作:\ r \ nUpdateFeature类型为WebGUI.Controllers.MyController \ r \ n \ nDeleteFeature .MyController“,”exceptionType“:”System.InvalidOperationException“,”stackTrace“:”.....
答案 0 :(得分:4)
您的路线错误,因为它未指定操作名称,因此它将UpdateFeature
部分视为ID参数。将其更改为:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
答案 1 :(得分:0)
最好使用Route
属性。
例如
[RoutePrefix("myapi")]
public class MyController : ApiController
{
[Route("update")]
[HttpPost]
public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
{
return new UpdateFeatureResponse { IsSuccess = true };
}
[Route("delete")]
[HttpPost]
public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
{
return new DeleteFeatureResponse{ IsSuccess = true };
}
}
现在在WebApiConfig
config.Routes.MapHttpRoute()
config.MapHttpAttributeRoutes();