简体   繁体   中英

Web api routing - default actions with custom actions mapped twice

I have the following routes mapped in my WebApiConfig:

config.Routes.MapHttpRoute(name: "WithActionApi", routeTemplate: "api/{controller}/{action}/{id}");
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { action = "DefaultAction", id = RouteParameter.Optional });

An in my controller I have:

[HttpGet]
public ProspectAddressResult Addresses(int id)
{
...
return result;
}

[ActionName("DefaultAction")]
public ProspectDetail Get(int id)
{
...
return prospect;
}

I'm finding that i'm getting the Get route mapped twice once as api/prospect/1 and api/prospect/Get/1. What am I doing wrong as I would expect the route to only be mapped once ie api/prospect/1 or is that not possible (or relevant)?

Why not just install web api 2 through nuget. Then you can use the Route and RoutePrefix properties on your actions/controllers to specify your routes.

You should then never get duplicate mapping

Here's an example of how your api controller would be set up:

[RoutePrefix("api/prospect")]
public class ProspectController: ApiController
{
    [Route("{id}")]
    public ProspectDetail Get(int id)
    {
        ...
        return prospect;
    }
}

Your route for that would then be api/prospect/1

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