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

Get Method Example in Asp.net 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="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>

Now let’s call the second overload get with a integer parameter
Call may look like http://localhost:53207/api/values/5
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">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 = "ratantata@tata.com" };
return c;
}

then we get result below, Remember if by default we get result in XML, when MediaTypeFormatter is XmlFormatter
http://localhost:53207/api/client/5
<Client xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WTRWebAPI">
<ClientId>1</ClientId>
<CompanyName>TATA Capital</CompanyName>
<ContactPerson>Ratan Tata</ContactPerson>
<Email>ratantata@tata.com</Email>
<Phone i:nil="true"/>
</Client>

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


Group Training