I have Googled tutorials about this web api because I only know how to create WCF Rest, but some questions I can't find the answer online so please bear with me.
To create my first Web API, I have use ASP.Net empty web applications project then added a new Web API (v1) class and proceeded to create several methods.
I have this routing in my Global.asax (Application_Start)
RouteTable.Routes
.MapHttpRoute("2", "AAA/{controller}/{action}/{var1}/{var2}", new { id = RouteParameter.Optional });
My questions are:
1. I can't access the URL if I use query string parameters like this first format /api/controllername/actionname?var1=123&var2=456 but this second format works /api/controllername/actionname/123/456. The first format only works if I add [FromUri] in each of the variables in the methods. So is this the way to do it when using query string, to add FromUri to make the routing works?
2. I read by default json is the mediatype format. If I want to allow user to select xml or json based on parameter type passed in the URL, how can I achieve this? I have added this code below in my Global.asax, but whatever value I pass that corresponds to formatType variable, json is still returned.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Clear();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type","json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
Here I have added the new variable formatType in route mapping, but still doesn't work. Can I add a if-then-else in Global.asax to check for formatType value and clear the media type that I don't want?
RouteTable.Routes
.MapHttpRoute("2", "AAA/{controller}/{action}/{formatType}/{var1}/{var2}", new { id = RouteParameter.Optional });
Thank you in advance.