Thursday, May 11, 2017

Interesting things about Web API in Asp.net MVC

Few things I learn in WEB API which is little interesting. I have spent lots of time to fix small issues and after doing google I found the solutions for those small issues, so I decided to document those solutions somewhere. The Blog is perfect place to document it so that I can refer it 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 production environment we have to call API from client applications. When I tried the same it was not working. 
Solution:  
                You need to enable CORS in order to allow remote call to your web API. 
  • Add System.Web.Http.Cors reference in your project. If you can't find it, add the nuget package for the same. 
  • Go to the  App_Start folder and click WebApiConfig.cs
  • Add these two lines in Register function
    • var cors = new EnableCorsAttribute("*","*","*");
                  config.EnableCors(cors);  // add this line of code to allow cross domain request
       
 
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. 
 Solution:
            You need to add Route attribute to tell MVC that this is my API here is the example
            [Route("api/Test/SubmitOrder")]
            public HttpResponseMessage SubmitOrder(FormDataCollection data)
           {
                     // your code goes here
           }

           Before you add Route attribute to your function, you need to add following line in your WebApiConfig.cs file 
            config.MapHttpAttributeRoutes();
 
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 returns data / list of data or string or integer or HttpResponseMessage either. 
 
Solution:
 
              You can include an object in your response like this.
               
        [Route("api/Test/SubmitOrderThreePara")]
        [HttpPost]
        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);

        } 



 
 
  
 
 
 


           
 

No comments:

Post a Comment