Here are a few things I learnt in WEB API which are a little interesting. I have spent lots of time fixing small issues and after some Googling, I found the solutions for those small issues, so I decided to document those solutions somewhere. The blog is a perfect place to document it so I can refer to it at any time.
Here is the list of issues and their solutions which I faced last night.
1) Not Able to Call WEB API from Client Application
When I started learning WEB API in ASP.NET MVC, I found most of the examples where the API has been called from the same project and it was working fine, but in the production environment, we have to call API from client applications. When I tried the same, it was not working.
You need to enable CORS in order to allow remote call to your web API.
2) Custom API Name Was Not Working
If you have taken the default template for Web API development, it won't allow you to use your favorite name for the API, for example, if you want to use
SubmitOrder for post API, it won't identify from client side call.
You need to add
Route attribute to tell MVC that this is my API. Here is the example:
public HttpResponseMessage SubmitOrder(FormDataCollection data)
Before you add
Route attribute to your function, you need to add the following line in your WebApiConfig.cs file.
3) How to Return Data / Object in HttpResponseMessage
It is always a best practice to return
HttpResponseMessage from your web API but how to return the data in the response? Most of the examples either return data / list of data or string or integer or
You can include an object in your response like this:
public HttpResponseMessage SubmitOrderThreePara(FormDataCollection frm)
Customer cm = new Customer();
cm.City = "Ahmedabad";
cm.ContactName = "Test User";
cm.Address = "Test Address";
return Request.CreateResponse(HttpStatusCode.OK, cm);