Support Ajax cross-domain access to ASP.NET Web Api 2 (Cors) simple sample tutorial demonstration

Support Ajax cross-domain access to ASP.NET Web Api 2 (Cors) simple sample tutorial demonstration

With the in-depth use of ASP.NET Web Api, we may consider dividing the front-end business into more detail 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 website project. Note that here are two Web site projects. The front-end project is mainly responsible for the presentation of the interface and some front-end corresponding business logic processing, while the Web Api is responsible for providing data.

So the problem comes, if the front end accesses the Web Api project through ajax, it involves cross-domain. We know that if it is accessed directly, Web Api is not allowed to do so under normal circumstances, which involves security issues. Therefore, the topic of our article today is to discuss and demonstrate how to configure Web Api to support cross-domain access (Cors). Okay, let's go directly to the subject of this article with a simple example.

First open Visual Studio 2013, create a blank solution, named: Solution.Cors.

Create an empty Web Api project and name it: CorsDemo.Api

Then we right click on the solution we just created

Create an empty Web site and name it: CorsDemo.UI

Well, after completing the above steps, you will see the following solution directory

Next, we use the Nuget package management tool to add the jQuery and Bootstrap packages we need in the website project of CorsDemo.UI (Bootstrap is mainly introduced to beautify our interface. Only one or two css classes can make a beautiful Beautiful buttons, as you will see below). The following is the interface to add the jQuery package

Refer to Bootstrap according to the method above. At this point, our preparations are complete. Let’s start to create a sample controller for Web Api: UserController. There is only one method that returns IEnumerable<T> in this controller. The specific code is as follows:

using CorsDemo.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CorsDemo.Api.Controllers
{
  [RoutePrefix("api/user")]
  public class UserController: ApiController
  {
    [HttpGet, Route("list")]
    public IEnumerable<User> GetUserList()
    {
      return new List<User> { 
        new User{Id=1,Name="Admin",Locked=false,CreateOn=DateTime.Now.ToShortDateString()},
        new User{Id=2,Name="Peter",Locked=false,CreateOn=DateTime.Now.ToShortDateString()},
        new User{Id=3,Name="Employee",Locked=true,CreateOn=DateTime.Now.ToShortDateString()}
      };
    }
  }
}

User class:

namespace CorsDemo.Api.Models
{
  public class User
  {
    public int Id {get; set;}
    public string Name {get; set;}
    public string CreateOn {get; set;}
    public bool Locked {get; set;}
  }
}

If we run the CorsDemo.Api project now and open the address: http://localhost:4543/api/user/list, we will see the output in XML format in the browser

Let's modify the WebApiConfig.cs file in the App_Start directory to let it output data in json format by default, as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;

namespace CorsDemo.Api
{
  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}/{id}",
          defaults: new {id = RouteParameter.Optional}
      );
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
  }
}

Regenerate the CorsDemo.Api project and open http://localhost:4543/api/user/list, then we can get the json data as follows:

[{"Id":1,"Name":"Admin","CreateOn":"2015/10/26","Locked":false},{"Id":2,"Name":"Peter", ”CreateOn”:”2015/10/26″,”Locked”:false},{“Id”:3,”Name”:”Employee”,”CreateOn”:”2015/10/26″,”Locked”: true}]

Okay, here we are ready to output the data on the Web Api side. In order to test whether it can be accessed across domains, we then go to the CorsDemo.UI website project. First create a cors-demo.html page (this name can be taken arbitrarily) and open it, and modify it to the following code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>Web Api 2 Cors Demo</title>
  <link href="Content/bootstrap.css" rel="stylesheet"/>
  <script src="Scripts/jquery-1.9.1.js"></script>
  <script src="Scripts/bootstrap.js"></script>
</head>
<body>
  <a class="btn btn-primary" id="getData">Get data across domains</a>
  <script type="text/javascript">
    $("#getData").click(function () {
      $.ajax({
        url: "http://localhost:4543/api/user/list",
        success: function (response) {
          console.log(response);
        }
      });
    });
  </script>
</body>
</html>

After completing the following steps, we right-click on cors-demo.html in Visual Studio, select "View in Browser" in the pop-up window, and Visual Studio will automatically be in the default browser (my browser here is Firefox) to open the cors-demo.html page. In order to test, we first click on the "Cross-domain access to data" button on this page (in order to see whether the Web Api supports cross-domain access at this time, we need to open the firebug plug-in of Firefox and locate the "Console" tab ).

After the ajax request is over

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4543/api/user/list. (Reason: CORS header'Access-Control-Allow-Origin' missing).

How about it, is it reminding us that the cross-domain request is blocked and the CORS header information is missing, so we can go to Web Api to configure CORS to support cross-domain access.

So now we go to the CorsDemo.Api project to configure CORS support. It doesn't need much, just configure the EnableCors method of HttpConfiguration in the WebApiConfig.cs file. Before modifying the configuration, we need to add some references through Nuget ( Microsoft.AspNet.WebApi.Cors,它的依赖包会被自动引用到项目中)

The modified WebApiConfig.cs file is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;

namespace CorsDemo.Api
{
  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}/{id}",
          defaults: new {id = RouteParameter.Optional}
      );
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
      var cors = new EnableCorsAttribute(
        origins: "*",
        headers: "*",
        methods: "*"
        );
      config.EnableCors(cors);
    }
  }
}

Now, we regenerate the CorsDemo.Api project and run it, and then click the button "Cross-domain data acquisition" on the page http://localhost:4631/cors-demo.html, through the firebug console, we can see the data Successfully loaded across domains

Well, this example and demonstration about ASP.NET Web Api supporting cross-domain requests is complete.

A few additions:

1. The parameters in the EnableCorsAttribute constructor can be set according to your own situation, such as origins, when it is "*", all domains can access api resources, if you only want the specified domain to access resources, specify Go to the specific domain

2. In the Web Api controller, we also restrict cross-domain access to a single Action. You only need to set the EnableCors property on the Action, such as:

[HttpGet]
[EnableCors("http://example.com","*","*")]
public User GetUser()
{
  return new User {Id = 1, Name = "Admin", Locked = false, CreateOn = DateTime.Now.ToShortDateString() };
}

Special note: The above is only an example of supporting Web Api cross-domain, and the existence of security verification and other issues are not mentioned. Therefore, if you need to use the technology in this article in a formal production project, please consider issues such as safety verification when you need it. Security issues, security issues, security issues. . . The important thing is said three times! ! !

Reference: https://cloud.tencent.com/developer/article/1034508 A simple example tutorial that supports Ajax cross-domain access to ASP.NET Web Api 2 (Cors)-Cloud + Community-Tencent Cloud