简体   繁体   中英

web api: Route different from name of controller, possible?

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

ie I try to get route not limit to controller name

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

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
    }
}

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.

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