0

I have mineController.cs now in my route, is it possible to do /api/mycontroller/myaction

i.e. I try to get route not limit to controller name

1

4 Answers 4

4

If you are using Web Api 2 you can use Attribute Routing for this:

[RoutePrefix("api/mine")]
public class mineController : ApiController
{
    [Route("method1")]
    [HttpGet]
    public IHttpActionResult Method1()
    {
        //Route would be api/mine/method1
    }

    [Route("method2")]
    [HttpGet]
    public IHttpActionResult Method2()
    {
        //Route would be api/mine/method2
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, by using Attribute Routing.

Step 1: Enable attribute routing in WebApiConfig.Register method (might be on by default, I don't recall offhand):

config.MapHttpAttributeRoutes();

Step 2: Not required, but it's nice to use a RoutePrefix attribute for the entire controller:

[RoutePrefix("api/mycontroller")
public class mineController : ApiController
{
    ..
}

Step 3: Use a Route attribute on each method that completes the route prefix:

[Route("myaction")]
[HttpGet] /* or other HttpVerb */
public IHttpActionResult SomeMethod()
{
   ...
}

[Route("myaction/{id}")]
[HttpGet] /* or other HttpVerb */
public IHttpActionResult SomeMethod(int id)
{
   ...
}

More info here: https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

1 Comment

Was missing the config setting. config.MapHttpAttributeRoutes. Thanks!
0

You can use the System.Web.Http.RouteAttribute to decorate your controller actions and specify any route you desire. Depending on what it is you want to do, this may be a good approach for you.

Comments

0

There is also the option of using a ~ to bypass the route prefix

take this from the ms documentation

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET /api/authors/1/books
    [Route("~/api/authors/{authorId:int}/books")]
    public IEnumerable<Book> GetByAuthor(int authorId) { ... }

    // ...
}

Comments

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.