创建名称相同但路由前缀不同的控制器
本文关键字:前缀 控制器 路由 创建 | 更新日期: 2023-09-27 18:15:43
我想创建两个api请求(c#和WebAPI)
1) http://localhost api/标题2) http://localhost api/定制/标题
在上面两个例子中,Title是我必须创建的控制器。因此,对于1个api,我创建了以下控制器
[RoutePrefix("api")]
public class TitleController : ApiController
{
[Route("Title")]
[HttpPost]
public IHttpActionResult Post(string programmeName, string titleType = "M", int estimatedDuration=0)
{
}
}
上面的控制器在'Title' titleccontroller .cs
对于我创建的2个api:
[RoutePrefix("api/Custom")]
public class TitleController : ApiController
{
[Route("Title")]
public IHttpActionResult Post([FromBody] TitleModel titleModel)
{
}
}
上述控制器位于'Custom'Title' titleccontroller .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'."
}
有时我得到一个错误说不止一个标题控制器存在,不允许。
如何解决这个问题,除了命名一个不同的控制器
删除约定路由
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 });