0

I created a web service using WEB API.

I'm using this routing configuration

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

And my solution include two controller (ProductController and DetailController)

So when I want to call a WS that refers to the GetDetails method(is located inside DetailController) I have to use a URL like this:

http://localhost/api/Details/GetDetails/?id=4

Is there a way for use, for the same request, this URL instead:

http://localhost/api/Product/GetDetails/?id=4

letting the GetDetails method inside the DetailController?

1 Answer 1

4

Actually your urls should be:

http://localhost/api/Details/4
http://localhost/api/Products/4

and your controllers:

public class DetailsController: ApiController
{
    public HttpResponseMessage Get(int id)
    {
        ...
    }
}

and:

public class ProductsController: ApiController
{
    public HttpResponseMessage Get(int id)
    {
        ...
    }
}

Now that's RESTful.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain the reasoning behind using query parameter instead of the url itself to represent the resource (ie http://localhost/api/Details/4). It doesn't seem "RESTful".
You are right. It's prettier to have /{id} in this case. But this doesn't mean at all that query string parameters are not RESTful. Usually when I have optional parameters I pass them as query string parameters. This usually makes sense in GET requests which need to take multiple parameters. But I agree with you that the identifier which identifies the resource is better to be passed in the path portion.
No, I understand the use case for query parameter. It just seemed like the id (in this case) was meant to represent a resource uniquely.
Completely agree with you. I have updated my answer to take your remark into account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.