Cross-domain call WEBAPI web-side cross-domain call WEBAPI

Source: Internet
Author: User

In web development, there are often cross-domain issues, so far there are a lot of cross-domain solutions. Through their own research and on the Internet to read some of the Great God's blog, wrote a demo first to create a new WEBAPI program, as shown: Because Microsoft has set up a WEBAPI environment for us, so we do not have to add reference to some DLLs, directly start to write code. Because it's just doing a simple demo, and there's no database attached. The first step is to add an entity class employees to the models folder to hold the data. The contents of the Employees.cs are as follows:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5   6 Namespace Apiapplication.models 7 {8 Public     class Employees 9     {ten public         int? Id {get; set;} One public         int? DepartmentID {get; set;} Public         string Name {get; set;} Public         string Job {get; set;} Public         string Gender {get; set;} Public         string Phonenum {get; set;} Public         string Emailadderss {get; set;} N-Public         string Address {get; set;}     }19}
After adding the entity class, our play is about to start, and that's the controller. Then we create a new control under the Controllers folder, Take the name Employeescontroller. Note When adding a controller, select the empty API controller template: In the controller we want to add the following code: Before adding the code we want to add a reference: using Apiapplication.models;
1 static list< employees> emps;2         static Employeescontroller () 3         {4             emps = new list< employees> () ; 5             Emps. ADD (new Employees {Id = 1, DepartmentID = 1, Name = "Zhang San", Gender = "male", Job = "ASP. NET Engineer ", Phonenum =" 1886                       0922483 ", Emailadderss =" [email protected] ", Address =" Jiangsu province Suzhou alone Lake Avenue No. 228 "}); 6             Emps. ADD (new Employees {Id = 2, DepartmentID = 2, Name = "John Doe", Gender = "female", Job = "web Front end engineer", Phonenum = "1886                       0922483 ", Emailadderss =" [email protected] ", Address =" No. 228, Lake Avenue, Suzhou, Jiangsu Province "}); 7         }
The purpose of this code is to store data in the Entity employees class. Here I only added two data for your reference only. Next we will implement the CRUD functionality:
1 public IEnumerable <employees > Get (int. id = null) 2         {3 Return from the             employee in Emps where employee. Id.equals (ID) | | String. IsNullOrEmpty (Convert. ToString (ID)) Select employee; 4         } 5 public         void Post (Employees employee) 6         {7             employee. Id = 3; 8             Emps. ADD (employee); 9         }10 public         void Put (Employees employee) One by one         {             emps. Remove (Emps. Where (E = = E.id = employee. ID). First ());             Emps. ADD (employee),         }15 public         void Delete (int id),             emps. Remove (Emps. Where (E = e.id = = Id). FirstOrDefault ());         
Here get is to get the employee incoming parameter ID is returned is the corresponding ID of the data, empty is all the data post is to add the data put is to modify the data put is very special, it is the modification of the time is based on the ID of the modified data to find this data, and then delete, add new data. Delete is, of course, deleted. The next is the time to witness miracles. We click Run, enter localhost:****/api/employees in the browser and we'll see an XML document like this: here we have done a few basic webapi get methods. Today we're talking about cross-domain calls WEBAPI what is cross-domain? JavaScript is not allowed to invoke objects of other pages across domains for security reasons. Generally, the cross-domain is divided into the following categories: On a cross-domain issue, the domain is only identified by the "header of the URL" and does not attempt to determine whether the same IP address corresponds to two domains or two domains on the same IP. To learn more about cross-domain students can access: http://twlidong.github.io/blog/2013/12/22/ Kua-yuan-zi-yuan-gong-xiang-cross-origin-resource-sharing-cors/understand the cross-domain we're going to start looking down. The web-side invocation API is divided into front-end calls (. net) back-end calls, which I start with AJAX about how to implement cross-domain first new MVC project, here I can not, I believe everyone will. Here we use the jquery Ajax () method, MVC defaults to help us introduce jquery we just need to write the following code:
1 <script> 2     $ (document). Ready (function () {3         $.ajax ({4             type: ' GET ', 5             URL: ' http://localhost : 7974/api/employees/get ', 6             dataType: ' JSON ', 7             success:function (data) {8                 alert ("Name:" + data[0]. Name + "Gender:" + data[0]. Gender + "Address:" + data[0]. Address); 9             }10         })     
Here the URL is the address map of your API/api/employee/get is called get method to get all the data in order to facilitate the demonstration I will get the data alert out. You must have failed in my steps. Let's think about why the following error message is explained here. Access-control-allow-origin is a server-side return response header defined in HTML5 that addresses cross-domain permissions issues for resources such as fonts. When Access-control-allow-origin is followed by a URL or *, if it is a URL it will only allow requests from that URL, * the request for any domain is allowed for example: header (' Access-control-allow-origin: Http://A.abc.com ') | | The header (' access-control-allow-origin:* ') means that you can only be accessed if the requested resource is allowed to cross the domain. So how do we set the Access-control-allow-origin? With this question, can I continue our tutorial in order to solve cross-domain problems we want to customize a Crosssite property to create a new class content in the project root directory as follows:
 1 using System.Web; 2 using System.Web.Http.Filters; 3 using SYSTEM.WEB.MVC;     4 5 Namespace Apiapplication 6 {7 public class CrossSiteAttribute:System.Web.Http.Filters.ActionFilterAttribute 8 {9 Private Const string origin = "origin";//&LT;SUMMARY&GT;11///Access-control-allow-o Rigin is a server-side return response header defined in HTML5 that addresses cross-domain permissions issues for resources such as fonts. ///&LT;/SUMMARY&GT;13 Private Const string accesscontrolalloworigin = "Access-control-allow-origin"; 1         4///&LT;SUMMARY&GT;15///Originheaderdefault The value can make the URL or *, if it is a URL will only allow requests from that URL, * allow any domain request 16 </summary>17 Private Const string originheaderdefault = "http://192.168.13.7:8002";///&L T;SUMMARY&GT;19////This method allows the API to support cross-domain calls from//</summary>21//<param name= "Actionexecutedcont Ext "> Initializes a new instance of the System.Web.Http.Filters.HttpActionExecutedContext class. </param>22 public override void onactionexecuted(Httpactionexecutedcontext ActionExecutedContext) @ actionExecutedContext.Response.Headers.Add (Ac Cesscontrolalloworigin, Originheaderdefault); 25}26}27}
Then we can add the [Crosssite] property to the Employeescontroller in the usage:
1 [crosssite]2 public  ienumerable<employees > Get (int-id = null) 3  {4    return from the employee in Emps whe Re employee. Id.equals (ID) | | String. IsNullOrEmpty (Convert. ToString (ID)) Select Employee;5  }
Then rebuild the solution and you can see the data for the warning box just after you run it. The front end call is over, let's see how the backend is called. In the models of the MVC project we need an entity model to read or set the data new class named V_employees
1 public class V_employees 2     {3 public         int? ID {get; set;} 4 public         int? DepartmentID {get; set;} 5         P Ublic string Name {get; set;} 6 public         string Job {get, set;} 7 public         string Gender {get; set;} 8         Publi C string Phonenum {get; set;} 9 public         string Emailadderss {get; set;} Ten public         string address {get; set;} One     }
The backend I used is httpclient specific usage is as follows:
1         Private HttpClient client = new HttpClient (); 2         private string url = "Http://192.168.13.7:8001/api/employees/g ET "; 3  4 public         async task< actionresult> Index () 5         {6             viewbag.message = "Modify This template to Jump-s Tart your ASP. NET MVC application. "; 7  8             var data = await client. Getasync (URL); 9             var employees = data. Content.readasasync<ienumerable <v_employees >> ();             list< v_employees> emps = employees. Result.tolist ();           One             viewdata["Employees"] = emps;12             return View ();         

Then set the ViewData on the index page

You can use the data emps directly on the page.

1 @foreach (var item in Emps) 2 {3     <ul >4         <li >@ item.name</li>5 <li         >@ ITEM.GENDER&L T;/li >6         <li >@ item.address</li >7     </ul >8}

The effect after operation is as follows:

Not to be continued.

This tutorial will be updated continuously.

Http://www.cnblogs.com/Leo_wl/p/4780650.html

http://hackervirus.byethost18.com/

http://www.cnblogs.com/Leo_wl/

Cross-domain call WEBAPI web-side cross-domain call WEBAPI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.