Search code examples
c#asp.net-web-apiattributerouting

WebAPI: What is the advantage of using Route attribute keyword


see the code first and it is taken from this area https://www.codeproject.com/Articles/1005485/RESTful-Day-sharp-Security-in-Web-APIs-Basic#_Toc423441907

[GET("productid/{id?}")]
[GET("particularproduct/{id?}")]
[GET("myproduct/{id:range(1, 3)}")]
public HttpResponseMessage Get(int id)
{}

[DELETE("remove/productid/{id}")]
[DELETE("clear/productid/{id}")]
[PUT("delete/productid/{id}")]
public bool Delete(int id)
{
 if (id > 0)
     return _productServices.DeleteProduct(id);
 return false;
}

the article show we can use http very to create route. if it is right then why should one use Route[] attribute keyword to define route for action or attribute routing ?

what is the advantage of using Route[] attribute keyword instead of define route using http verb ?

please guide me. thanks


Solution

  • HTTP verb itself work as route in web api but if that is not enough and you want your own route for your resource Route[] attribute is used. See this question url in SO. If HTTP verb was used to retrieve this question URL would be like https://stackoverflow.com/questions/get/44454705

    but instead SO used Route attribute to make URL more clear by removing get in url and passing question header in url

    Update : Taking following web api controller

    public class QuestionController: ApiController
    {
      public string Get(int id)
      { 
        return "";
      }
    
      [Route("questions/{id}/{question}")]
      public string GetRoutedQuestion(int id)
      {
        return "";
      }
    }
    

    So in above web api controller to call Get method your url will be like

    yourdomain/api/question/get/1
    

    Here api after domain gets added because of web api route config file's default route rule.

    But to call GetRoutedQuestion your url will be

    yourdomain/question/1/question-text
    

    if you like former url you can stick with HTTP verbs but if you want to customize your url you have to use custom routing either that be in attribute route or in route config file.