Wednesday, 4 January 2017

WEB API in ASP.NET MVC - Simple Website to Cross domain

For This we have to create two project one project will return our data and other will read it using web api. So lets create first application after that we will create another.


start a new mvc4 Application 









Add an empty webapi controller by right clicking on Controller folder




Add following codes in controller

  Create some array,list or json return data from database.
In below code i am returning a list of datatable item through selectListItem.
You can use any return type.

Add below code in your controller these are default functions for a web api


   public IEnumerable<SelectListItem> Get()
        {
            System.Data.DataTable dt = WebapiTest.Models.Procedures.ProductList();
            List<SelectListItem> Status = new List<SelectListItem>();
            foreach (System.Data.DataRow drow in dt.Rows)
            {
                 Status.Add(new SelectListItem 
                   { Text = drow["productName"].ToString(),
                     Value = drow["ourPrice"].ToString() 
                    });
            }
            return Status;
        }
        public string Get(int id)
        {
            return "value";
        }
         //POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }


Get will be default for api controller.
as here my webapiConfig.cs contain 
  
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

So our default routing will be

api/controllername/   for get
api/controllername/5   for get(id)
  
To see it in working we can directly browse with above url and it will return data in which format get will give like below:




More important of web api comes in use when we want to run it in cross domain sites whatever that is webapi or asp.net mvc4 sites.

One thing we have to keep remember we can't get our api data on cross domain(another website) without hosting it to iis so first host it.

To host just open IIS Internet Information Service by typing inetmgr on start. Once opened add new site name it. 



and browse on your port and ip as 

http://10.0.0.13:84/api/MyApi/

In case if it not runs open your window turn feature on off and switch asp.net services on then check. If still not run Go to your Apllication Pool in top of iis



double click on it 



Select your version in which your project was made or choose pipeline mode and click ok.

Then browse, In my case it run after fixing each small iis errors .


After that Create another MVC4 project name it as i make it apiReader.

For creating project we will follow same rule that i mentioned in start.
This time we will not add any api controller we will read our api data directly in this page.
To do that i have called api directly in an ajax call as

<script type="text/javascript">
    $(function () {
        $.getJSON('/api/MyApi/', function (contactsJsonPayload) {
            $(contactsJsonPayload).each(function (i, item) {
                $('#contacts').append('<li>' + item.Text + '</li>');
            });
        });
    });
</script>

But it didn't return anything incase it gives error



I had searched about it but google gives suggestion to use weapi.cors assemblies, and when i install it .It distroyed my api dll by version issues



Later i learned it is not so easy to get directly in javscript ajax or getjson or xhr. 
To use api data we have to read it with HttpWebRequest by below service i learned by seniors.

  public static string GetResponse(string sURL)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
            request.MaximumAutomaticRedirections = 4;
            request.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                string sResponse = readStream.ReadToEnd();
                response.Close();
                readStream.Close();
                return sResponse;
            }
            catch
            {
                return "";
            }
        }
They told me to keep it remember that by using 

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL)

we can do variours operations on request.
like security,pipeline,redirects and many more as
 request.ContentType , request.ClientCertificates, request.CachePolicy
request.AuthenticationLevel , request.AllowWriteStreamBuffering

Now just paste above function in controller

call it in any ActionResult like

 public ActionResult About()
        {
// Url with ip because we are reading cross domain api
            string sURL = "http://10.0.0.13:84/api/MyApi";

/////  Now a call to above function with our api url and it will return response
            string sResponse = GetResponse(sURL);

/////  Storing in viewbag.
            ViewBag.res = sResponse;

            return View();
        }
Now we can call it in our ajax also.
Let's check how we can now return it in ajax.
Add About view >>>>  Keep its  layout null >>> and does not give any space and only put your viewbag in it as given below:
@{Layout = null;}@ViewBag.res

If you open your about page directly you will get like this



Your data will look like json. But if you have keep extra space on about view with layout null then it comes a issue while reading json, so avoid spaces only write 
@{Layout = null;}@ViewBag.res



Now add another action result or just go with index page.
Here i am reading my api values on index page by below code.

<div id="body">
    <ul id="contacts"></ul>
</div>
<script src="/Scripts/jquery-1.8.2.min.js"></script>

<script type="text/javascript">

    $(function () {

        $.getJSON('/api/MyApi/', function (contactsJsonPayload) {
            $(contactsJsonPayload).each(function (i, item) {
                $('#contacts').append('<li>' + item.Text + '</li>');
            });
        });
    });
</script>

This will give:

And here we get our api from cross domain sites to another domain sites.

This is the whole basic i have to do with web api.
I will return soon with some web api nice stuffs..




0 comments:

Post a Comment