Web Api 2 (Cors) Ajax cross-domain access

Source: Internet
Author: User

With an in-depth use of the ASP. NET Web Api, we might consider taking the front-end business to a finer point in the project. For example, the front-end project uses the ANGULARJS framework to make the UI, and the data is supported by another Web Api's Web site project. Note that this is the two Web site project, the front-end project is responsible for the interface rendering and some front-end corresponding business logic processing, while the Web API is responsible for providing data.

The problem is that if the frontend accesses the Web API project session through AJAX, it involves cross-domain. We know that, if accessed directly, the Web API is normally not allowed to do so, which involves security issues. So, the topic of our article today is a discussion that demonstrates how to configure the Web API to support cross-domain access (Cors). OK, let's go straight 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 you just created, create an empty Web project to impersonate our site to cross-domain calls to the WEBAPI project, as follows:

After completing the above steps, our solution directory looks like this:

Here we add jquery through NuGet in the Web project of the mock Web site, which is the interface for adding jquery packages:

Once the additions are complete, we have finished the preparatory work here. The following is an entity class userinfo that is added to the Models folder of the WEBAPI project, with the following code:

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 in the WEBAPI project: Userinfocontroller, which is used to return the data collection, with the following code:

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>///How to obtain a collection of user information//</summary>            <returns> return user information collection </returns> public Ihttpactionresult GetList () {//object collection simulation data                list<userinfo> list = new list<userinfo> () {New UserInfo ()                    {Id = 1, UserName = "Zhang San", Userpass = "Fdasdfas", Email = "[email protected]", Regtime = DateTime.Now}, new Useri NFO () {Id = 2, UserName = "John Doe", Userpass = "fdasd FAS ", Email =" [email&Nbsp;protected] ", Regtime = DateTime.Now}, new UserInfo ()                    {Id = 3, UserName = "Harry", Userpass = "Fdasdfas", Email = "[email protected]", Regtime = DateTime.Now}, new User Info () {Id = 4, UserName = "Zhao Liu", Userpass = "FDAs                DFAs ", Email =" [email protected] ", Regtime = DateTime.Now},                    New UserInfo () {Id = 5, UserName = "Tianqi",                 Userpass = "Fdasdfas", Email = "[email protected]", Regtime = DateTime.Now  }, New UserInfo () {Id = 6, UserName =                  "Wang Ba",  Userpass = "Fdasdfas", Email = "[email protected]", Regtime = DateTime.Now            }            };        return Ok (list); }    }}

Then we need to modify the WebApiConfig.cs file in the App_start directory Webapi routing rules in order to access through api/{controller}/{action}, while allowing the modification of the serialization mode, Let WEBAPI output JSON-formatted data by default, with the following details:

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 JSON-formatted serializer            CONFIG. Formatters.add (New Jsonmediatypeformatter ());}}}    

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

[{"Id": 1, "UserName": "Zhang San", "Userpass": "Fdasdfas", "email": "[email protected]", "Regtime": "2016-04-21t10 : 36:50.7800569+08:00 "},{" Id ": 2," UserName ":" John Doe "," Userpass ":" Fdasdfas "," email ":" [email protected] "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 3," UserName ":" Harry "," Userpass ":" Fdasdfas "," email ":" [email protected] "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 4," UserName ":" Zhao Liu "," Userpass ":" Fdasdfas "," email ":" [email Protected] "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 5," UserName ":" Tianqi "," Userpass ":" Fdasdfas "," Email ":" [email protected] "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "},{" Id ": 6," UserName ":" Wang Ba "," Userpass ":" Fdasdfas "," email ":" [email protected] "," Regtime ":" 2016-04-21t10:36:50.7800569+08:00 "}]

Well, here we have the data output on the Web API side ready. To test whether cross-domain access is possible, we then go to the Corsdemo.ui Web site project. First create a index.aspx page (this name can be arbitrarily taken) after opening, modified to the following code:

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

After completing the above steps, launch the WEBAPI project and Web project and click the cross-domain Get Data button on the Web project's index page to open the browser console to view the results of the request, and the following results appear in the console:

The console prompts us to block cross-domain requests and prompts for Cors header information, so we can configure Cors to support cross-domain access by going to WEBAPI.

Now let's add Microsoft.AspNet.WebApi.Cors through NuGet in the WEBAPI project, and then configure the Enablecors method of httpconfiguration in the WebApiConfig.cs file. Here's how:

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 Enablecrosssite            Requests (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 JSON-formatted serializer CONFIG.        Formatters.add (New Jsonmediatypeformatter ()); }///<summary>//Allow cross-domain calls///</summary>//<param name= "config" ></para m> private static void Enablecrosssiterequests (HttpconfiguratIon config) {//For all request sources without any restrictions var cors = new Enablecorsattribute (Origins: "*",            Headers: "*", Methods: "*"); Config.        Enablecors (cors); }    }}

Now, we re-build the WEBAPI project and run it, then click the button "Get Data Across Domains" in page http://localhost:31521/Index.aspx, through the Firebug console, we can see that the data cross-domain loading was successful, as follows:

At this point, examples and demos of the ASP. NET Web API support cross-domain requests are complete.

Category: WebAPI

Web Api 2 (Cors) Ajax cross-domain access

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.