>>Hi,
>>
>>I created a HelloWorld Web API solution in VS 2013. I left all the code automatically created by VS unchanged.
>>On executing of this project the VS opens the browser and puts the following URL: "localhost:53757" which shows a descriptive ASP.NET page created by VS.
>>Then when I add "/api/values" to this URL making it "localhost:53757/api/values" and the browser returns the array of two values (from the Controller class).
>>
>>I would like to understand better the WebApiConfig class which is in the APP_START folder. This class calls method Register and passes the HttpConfiguration config. I have two questions, please:
>>
>>1. Do I understand correctly that this class (WebApiConfig) and method are called ONLY ONE TIME when you start the Web API (project)? Why I think so: I set a debug point in this class, and the debug point is hit only once when I execute the proejct. When I add the "/api/values" to the localhost:53757 (making it localhost:53757/api/value) code in the class WebApiConfig does not fire and debut point is not hit.
>>
>>2. Below is the code of the WebApiConfig class. Could someone please explain it - in English - as simply as possible (if possible).
>>
>>
>> public static class WebApiConfig
>> {
>> public static void Register(HttpConfiguration config)
>> {
>> // Web API configuration and services
>>
>> // Web API routes
>> config.MapHttpAttributeRoutes();
>>
>> config.Routes.MapHttpRoute(
>> name: "DefaultApi",
>> routeTemplate: "api/{controller}/{id}",
>> defaults: new { id = RouteParameter.Optional }
>> );
>> }
>> }
>>
>>
>
>I have a question related to the Controller class. I thought I would start a new thread but since it is part of the same project that uses the class WebApiConfig (above), I am posting my question here.
>
>When I enter in the browser the URL localhost:53757/api/value the browser returns 2 values ('value1' and 'value2'). The controls class from where these values are taken are below:
>
>
> public class ValuesController : ApiController
> {
> // GET api/values
> public IEnumerable<string> Get()
> {
> return new string[] { "value1", "value2" };
> }
>
> // GET api/values/5
> public string Get(int id)
> {
> return "value";
> }
>
>
>I don't understand why the URL that has the key word 'value' fires the method Get() above? I don't see the word 'value' anywhere in this class. What am I missing?
As early using MapHttpRoute() can be hard to debug/understand. Do yourself a favour and stay away from it. Your class should work as expected using attributes instead:
[RoutePrefix("api")]
public class ValuesController : ApiController
{
[Route("values")]
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[Route("values/{id}")]
[HttpGet]
public string Get(int id)
{
return "value";
}
}
Note that the actual method name is irrelevant from a WebApi POV.