简体   繁体   English

创建具有相同名称但路径前缀不同的其他控制器

[英]Creating different controller with same name but different route Prefix

I want to create two api requests (in C#, WebAPI) 我想创建两个api请求(在C#,WebAPI中)

1) http://localhost:port/api/Title 2) http://localhost:port/api/Custom/Title 1) http:// localhost:port / api /标题 2) http:// localhost:port / api / Custom /标题

In both the above cases, Title is controller which I have to create. 在以上两种情况下,标题都是我必须创建的控制器。 So for 1 api I created the following controller 因此,对于1个api,我创建了以下控制器

[RoutePrefix("api")]
public class TitleController : ApiController
{
    [Route("Title")]
    [HttpPost]
    public IHttpActionResult Post(string programmeName, string titleType = "M", int estimatedDuration=0)
   {
   }
}

The above controller is in \\Title\\TitleController.cs 上面的控制器位于\\ Title \\ TitleController.cs中

For 2 api I created below: 对于下面创建的2个api:

[RoutePrefix("api/Custom")]
public class TitleController : ApiController
{
    [Route("Title")]
    public IHttpActionResult Post([FromBody] TitleModel titleModel)
    {
    }
}

The above controller is in \\Custom\\Title\\TitleController.cs 上面的控制器位于\\ Custom \\ Title \\ TitleController.cs中

And I have configured my WebApiConfig.cs to have both routes 而且我已经将我的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);
    }
}

When I make a call to api 2, I get the following error 调用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'."
}

ANd sometimes I get an error saying more than one Title Controller exists and not allowed. 有时我会收到一条错误消息,说存在多个标题控制器,并且不允许使用。

How do I resolve this issue, other than naming one of the controller differently 我如何解决此问题,除了以不同的方式命名一个控制器外

Remove the convention routing you have 删除您拥有的约定路由

 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 });

and just use the attribute routing in your classes. 并在类中使用属​​性路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM