Example tutorials to support Ajax cross-domain access asp.net Web Api 2 (Cors) _ Practical Tips

Source: Internet
Author: User
Tags serialization static class

With the deep use of the ASP.net Web Api, we might consider splitting the front-end business into finer points in the project. For example, the front-end project uses the ANGULARJS framework to do the UI, and the data is supported by a Web site project for another Web Api. Note that here are two Web site projects, the front-end project is mainly responsible for the interface rendering and some front-end of the corresponding business logic processing, and the Web API is responsible for providing data.

This is the problem, if the front-end through AJAX access to Web API project words, it involves cross-domain. We know that if you are accessing directly, the Web API is normally not allowed to do this, which involves security issues. So, the topic of our article today is to discuss how to configure the Web API to support Cross-domain access (Cors). OK, let's go directly to the subject of this article with a simple example.

First open Visual Studio 2013 and create a blank solution named: Crossdomainaccesswebapi.

Then create an empty Web API project named: CROSSDOMAINACCESS.WEBAPI

Then we right-click the solution we just created and create an empty Web project to simulate our web site for Cross-domain calls to the WEBAPI project, as follows:

After completing these steps, our solution catalog is shown in the following illustration:

Here we add jquery to the Web project of the mock Web site via NuGet, which is the interface to add the jquery package:

After the addition is complete, we have finished the preliminary preparation work here. The following is added to the Models folder of the WEBAPI project is an entity class UserInfo, as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace CrossDomainAccess.WebAPI.Models
{public
 class UserInfo
 {public
  int Id {get; set;}

  public string UserName {get; set;}

  public string Userpass {get; set;}

  public string Email {get; set;}

  Public DateTime regtime {get; set;}}}


Then add a sample controller to the WEBAPI project: Userinfocontroller, which is used to return the data collection, as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Http;
Using System.Web.Http;

Using CrossDomainAccess.WebAPI.Models; 
  Namespace CrossDomainAccess.WebAPI.Controllers {public class Userinfocontroller:apicontroller {///<summary> Ways to get a collection of user information///</summary>///<returns> return user information collection </returns> public Ihttpactionresult getlist
     () {//object collection analog data list<userinfo> List = new list<userinfo> () {new UserInfo () {Id = 1,
    UserName = "John", Userpass = "Fdasdfas", Email = "zhangsan@163.com", Regtime = DateTime.Now}, New UserInfo () {Id = 2, UserName = "Dick", Userpass = "Fdasdfas", Email = "lisi@163.com", Regt IME = DateTime.Now}, new UserInfo () {Id = 3, UserName = "Harry", Userpass = "Fdasdfas", Ema
Il = "wangwu@163.com", Regtime = DateTime.Now}, new UserInfo () {Id = 4,     UserName = "Zhao Liu", Userpass = "Fdasdfas", Email = "zhaoliu@163.com", Regtime = DateTime.Now}, n EW UserInfo () {Id = 5, UserName = "Tianqi", Userpass = "Fdasdfas", Email = "tianqi@163.com", Reg Time = DateTime.Now}, new UserInfo () {Id = 6, UserName = "King Eight", Userpass = "Fdasdfas", Em
   ail = "wangba@163.com", Regtime = DateTime.Now}};
  return Ok (list);
 }
 }
}

Then we need to modify the routing rules of the WEBAPI in the WebApiConfig.cs file in the App_start directory so that we can access them through api/{controller}/{action}, and let's modify the serialization mode, Let WEBAPI output JSON-formatted data by default, as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net.Http.Formatting;
Using System.Web.Http;

Namespace Crossdomainaccess.webapi
{public
 static class Webapiconfig
 {public
  static void Register ( Httpconfiguration config)
  {
   //Web API Configuration and service

   //Web API Routing
   config. Maphttpattributeroutes ();

   Config. Routes.maphttproute (
    name: "Defaultapi",
    routetemplate: "Api/{controller}/{action}/{id}",
    defaults:new {id = routeparameter.optional}
   );
   Clears all serialization format
   CONFIG. Formatters.clear ();
   Adds a serializer config in JSON format
   . Formatters.add (New Jsonmediatypeformatter ());}}

Regenerate the project and access it in the browser, we can get the data in JSON format as follows:

Copy Code code as follows:
[{"Id": 1, "UserName": "John", "Userpass": "Fdasdfas", "Email": "Zhangsan@163.com", "Regtime": "2016-04-21t10 : 36:50.7800569+08:00 "},{" Id ": 2," UserName ":" Dick "," Userpass ":" Fdasdfas "," Email ":" Lisi@163.com "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id: 3, "UserName": "Harry", "Userpass": "Fdasdfas", "Email": "Wangwu@163.com", " Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 4," UserName ":" Zhao Liu "," Userpass ":" Fdasdfas "," Email ":" Zhaoliu@163.com "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 5," UserName ":" Tianqi "," Userpass ":" Fdasdfas ", "Email": "Tianqi@163.com", "Regtime": "2016-04-21t10:36:50.7800569+08:00"},{"Id": 6, "UserName": "Wang Eight", "Userpass": " Fdasdfas "," Email ":" Wangba@163.com "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "}]

Well, here we have the data output from the Web API side ready. To test for cross-domain access, we then go to the Corsdemo.ui Web site project. First create a index.aspx page (this name can be arbitrarily taken) and then open it and modify it to the following code:

 <%@ Page language= "C #" autoeventwireup= "true" codebehind= "Index.aspx.cs" inherits= "CrossDomainAccess.Web.Index"%> <! DOCTYPE html>  
 

When you are done, start the WEBAPI project and the Web project, click the Cross-domain Fetch button in the index page of the Web project, open the browser console to view the request results, and the following results appear in the console:

The console prompts us to block Cross-domain requests and prompts Cors header information Indeed, so we can webapi configure Cors to support Cross-domain access.

So now we add Microsoft.AspNet.WebApi.Cors through NuGet in the WEBAPI project and then configure Httpconfiguration enablecors methods in the WebApiConfig.cs file. The specific actions are as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net.Http.Formatting;
Using System.Web.Http;

Using System.Web.Http.Cors; namespace Crossdomainaccess.webapi {public static class Webapiconfig {public static void Register (httpconfiguration
   Config) {//Web API Configuration and service enablecrosssiterequests (config); Web API Routing config.

   Maphttpattributeroutes (); Config.  Routes.maphttproute (Name: "Defaultapi", Routetemplate: "Api/{controller}/{action}/{id}", defaults:new {id =
   Routeparameter.optional}); Clears all serialization format CONFIG.
   Formatters.clear (); Adds a serializer config in JSON format.
  Formatters.add (New Jsonmediatypeformatter ()); ///<summary>///allow Cross-domain calls///</summary>///<param name= "config" ></param> private sta
    tic void enablecrosssiterequests (httpconfiguration config) {//no restriction on all source of request var cors = new Enablecorsattribute (
   Origins: "*", Headers: "*", Methods: "*"); Config. ENablecors (cors);
 }
 }
}

Now, we'll rebuild the WEBAPI project and run it, then click the button "Cross-domain fetch data" in the page http://localhost:31521/Index.aspx, and through the Firebug console, we can see that the data has been loaded across the domain successfully, as follows:

For more highlights, please click on the "Ajax cross-Domain technology summary" for in-depth study and research.

So far, the example and demo of the ASP.net Web API supporting Cross-domain Requests is complete, thanks for reading.

Related Article

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.