c# - How do I write REST service to support multiple Get Endpoints in .net MVC Web API? -
so familiar how write default get, post, put, delete
//get api/customer public string get(){} //get api/customer/id public string get(int id){} //post api/customer public void post([frombody]string value){} //put api/customer/id public void put(int id, [frombody]string value){} //delete api/customer/id public void delete(int id){}
but how write add endpoint w/o having create whole new controller? want grab customer's metadata? need make changes routeconfig? if how that? , how use new route in javascript?
//get api/customer/getmetadata public string getmetadata(){ }
you use attribute route. attribute added in webapi 20 , can use @ method level define new route or more routes , way use [route("url/route1/route1")]
:
using 1 of examples above like:
//get api/customer/getmetadata [route("api/customer/getmetadata")] public string get2(){ //your code goes here }
if declaring several routes in class can use routeprefix attribute [routeprefix("url")]
@ class level. set new base url methods in controller class.
for example:
[routeprefix("api2/some")] public class somecontroller : apicontroller { // api2/some [route("")] public ienumerable<some> get() { ... } // api2/some/5 [route("{id:int}")] public get(int id) { ... } }
note: in example above showed 1 example route allowed set type constraints well.
Comments
Post a Comment