Online Training for MVC Web Designing Development, MS SQL, Digital Marketing

Get Method Example in Web API

Once we create a webApi project, we can see there is a "ValuesController" created with two get methods
Now if you notice, the ValuesController is inherited from System.Web.Http.ApiController, when the HomeController in same folder is inherited from System.Web.Mvc.Controller

So ValuesController is our WebApi controller, now let's look at get methods inside, One with parameter and another without parameter
public class ValuesController : System.Web.Http.ApiController
// GET api/values
public IEnumerable<string> Get()
return new string[] { "value1", "value2" };

// GET api/values/5
public string Get(int id)
return "value";

Take a look at the "App_Start/ WebApiConfig.cs" file, before you compile and run the default Web API
After root it starts with “api/” then controller name, in this case "values", url may look like http://localhost:53207/api/values/
By default, the first get method will be executed, which will returns a string arrays
<ArrayOfstring xmlns:i="" xmlns="">

Now let’s call the second overload get with a integer parameter
Call may look like http://localhost:53207/api/values/5
<string xmlns="">value </string>

Now in get method we can return any custom object (example "Client")
public Client Get(int id)
Client c = new Client() { ClientId = 1, CompanyName = "TATA Capital", ContactPerson = "Ratan Tata", Email = "" };
return c;

then we get result below, Remember if by default we get result in XML, when MediaTypeFormatter is XmlFormatter
<Client xmlns:i="" xmlns="">
<CompanyName>TATA Capital</CompanyName>
<ContactPerson>Ratan Tata</ContactPerson>
<Phone i:nil="true"/>

But when MediaTypeFormatter is JsonFormatter, then the result will be JSON format
{"ClientId":1,"CompanyName":"TATA Capital","ContactPerson":"Ratan Tata","Email":"","Phone":null}
Asp.Net Web API Get Example

Group Training