简体   繁体   中英

Route Prefix VS Controller Name ( Web api )

I was wondering that if we use RoutePrefix attribute in our web api controller with a different name from controller's actual name. So would it work or not?

As far as i did

[RouterPrefix("quotation")]
public class SaleOrderController : ApiController { ... }

if we define RoutePrefix like above we can't access it via /quotation but we can access it using saleorder .

So what is RoutePrefix for or am i doing something wrong ?

To use default route use Route("")

[RoutePrefix("quotation")]
public class SaleOrderController : ApiController {

    //GET quotation
    [Route("")]
    [HttpGet]
    public IHttpActionResult GetAll() { ... }

}

Source: Attribute Routing in ASP.NET Web API 2 : Route Prefix

In order for it to work, you need to call the code below inside your WebApiConfig.Register() method:

config.MapHttpAttributeRoutes();

So your RoutePrefix works as exptected:

[RoutePrefix("quotation")]
public class SaleOrderController : ApiController
{
    [Route("example")]
    [HttpGet]
    public IHttpActionResult Example()
    {
        return Ok();
    }

    [Route("another")]
    [HttpGet]
    public IHttpActionResult Another()
    {
        return Ok();
    }

}

So your could access your apis like this:

  • quotation/example
  • quotation/another

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