質問

I have this requirement to map the url

api/v1/Contact/12/tags

in the above url the Contact is the controller, and 12 is the contactId and tags is the action is want to be called.

The method is like this

[HttpGet]
public List<TagModel> Tags([FromUri]int contactId)

I have did like this

 config.Routes.MapHttpRoute(
                name: "RouteForHandlingTags",
                routeTemplate: "api/v1/{controller}/{id}/{action}",
                defaults: new { },
                constraints: new { id = @"\d+" }
                );

I am getting the error "No HTTP resource was found that matches the request URI http://localhost:4837/api/v1/contact/12/tags"

I have tried

[HttpGet]
public List<TagModel> Tags(int contactId)

and

 config.Routes.MapHttpRoute(
                    name: "RouteForHandlingTags",
                    routeTemplate: "api/v1/{controller}/{id}/{action}"
                    );

But all are giving the same error. But when I do a call like this

api/v1/Contact/12/tags?contactid=12

everything works fine. But this is not what I want. The contactId is specified after contact. Can anyone please tell me how to route this?

役に立ちましたか?

解決

The parameter names in your action and route must match. You can either change your action to:

[HttpGet]
public List<TagModel> Tags(int id)

Or change your route to:

config.Routes.MapHttpRoute(
    name: "RouteForHandlingTags",
    routeTemplate: "api/v1/{controller}/{contactId}/{action}",
    defaults: new { },
    constraints: new { id = @"\d+" }
    );

Note: you do not need [FromUri] with a primitive type like an int.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top