我想创建两个api请求(在C#,WebAPI中)
1)http://localhost:port/api/Title 2)http://localhost:port/api/Custom/Title
在上述两种情况下,Title都是我必须创建的控制器。所以对于1 api,我创建了以下控制器
[RoutePrefix("api")]
public class TitleController : ApiController
{
[Route("Title")]
[HttpPost]
public IHttpActionResult Post(string programmeName, string titleType = "M", int estimatedDuration=0)
{
}
}
以上控制器位于\ Title \ TitleController.cs
我在下面创建了2个api:
[RoutePrefix("api/Custom")]
public class TitleController : ApiController
{
[Route("Title")]
public IHttpActionResult Post([FromBody] TitleModel titleModel)
{
}
}
以上控制器位于\ Custom \ Title \ TitleController.cs
中我已将WebApiConfig.cs配置为具有两个路径
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(name: "CustomApi", routeTemplate: "api/Custom/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
FilterConfig.RegisterGlobalFilters(config);
RouteConfig.RegisterRoutes(config);
}
}
当我打电话给api 2时,我收到以下错误
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:872/api/Custom/Title'.",
"MessageDetail": "No type was found that matches the controller named 'Custom'."
}
有时候我会收到错误,说存在多个Title Controller并且不允许。
除了以不同方式命名控制器之外,我该如何解决此问题
答案 0 :(得分:0)
删除您拥有的约定路由
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(name: "CustomApi", routeTemplate: "api/Custom/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
只需在您的课程中使用属性路由。