简体   繁体   中英

Creating different controller with same name but different route Prefix

I want to create two api requests (in C#, WebAPI)

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

In both the above cases, Title is controller which I have to create. So for 1 api I created the following controller

[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

For 2 api I created below:

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

The above controller is in \\Custom\\Title\\TitleController.cs

And I have configured my WebApiConfig.cs to have both routes

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

{
   "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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