Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of supporting Ajax Cross-domain access to ASP.NET Web Api 2

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "sample analysis of supporting Ajax cross-domain access to ASP.NET Web Api 2", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of supporting Ajax cross-domain access to ASP.NET Web Api 2".

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

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 website to make cross-domain calls to the WebAPI project, as follows:

After completing the above steps, our solution directory is shown in the following figure:

Below, we add jQuery through Nuget in the Web project of the simulation website. Here is the interface for adding jQuery package:

After the addition is completed, we have completed the preliminary preparatory work here. Add an entity class UserInfo to the Models folder of the WebAPI project 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 set, 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: the method of ApiController {/ returns the user information collection public IHttpActionResult GetList () {/ / object collection simulation data List list = new List () {new UserInfo () {Id = 1, UserName = "Zhang San", UserPass = "FDASDFAS", Email = "zhangsan@163.com" RegTime = DateTime.Now}, new UserInfo () {Id = 2, UserName = "Li Si", UserPass = "FDASDFAS", Email = "lisi@163.com", RegTime = DateTime.Now}, new UserInfo () {Id = 3, UserName = "Wang Wu", UserPass = "FDASDFAS", Email = "wangwu@163.com", RegTime = DateTime.Now} New UserInfo () {Id = 4, UserName = "Zhao Liu", UserPass = "FDASDFAS", Email = "zhaoliu@163.com", RegTime = DateTime.Now}, new UserInfo () {Id = 5, UserName = "Tian Qi", UserPass = "FDASDFAS", Email = "tianqi@163.com", RegTime = DateTime.Now}, new UserInfo () {Id = 6 UserName = "bastards", UserPass = "FDASDFAS", Email = "wangba@163.com", RegTime = DateTime.Now}} Return Ok (list);}

Next, we need to modify the routing rules of webapi in the WebApiConfig.cs file in the App_Start directory to access through api/ {controller} / {action}. At the same time, we need to modify the serialization method and let WebAPI output data in json format 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) {/ / WebAPI configuration and service / / WebAPI routing config.MapHttpAttributeRoutes (); config.Routes.MapHttpRoute (name: "DefaultApi", routeTemplate: "api/ {controller} / {action} / {id}", defaults: new {id = RouteParameter.Optional}) / / clear all serialization formats config.Formatters.Clear (); / / add serializer config.Formatters.Add (new JsonMediaTypeFormatter ()) in Json format;}

Rebuild the project and access it in the browser. At this time, we can get the data in json format as follows:

The copy code is as follows:

[{"Id": 1, "UserName": "Zhang San", "UserPass": "FDASDFAS", "Email": "zhangsan@163.com", "RegTime": "2016-04-21T10:36:50.7800569+08:00"}, {"Id": 2, "UserName": "Li Si", "UserPass": "FDASDFAS", "Email": "lisi@163.com", "RegTime": "2016-04-21T10:36:50.7800569+08:00"}, {"Id": 3, "UserName": "Wang Wu" "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": "son of a bitch", "UserPass": "FDASDFAS", "Email": "wangba@163.com", "RegTime": "2016-04-21T10:36:50.7800569+08:00"}]

All right, at this point, the data output on our Web Api side is ready. To test whether it can be accessed across domains, let's go to the CorsDemo.UI website project. First, create an index.aspx page (you can choose this name yourself), open it, and modify it to the following code:

(function () {$('# getData') .click (function () {$.ajax ({url: 'http://localhost:29867/api/UserInfo/getlist', dataType:' json', success: function (data) {/ / display data in the browser console in tabular form, console.table (data) is not supported under IE;})

After completing the above steps, launch the WebAPI project and the Web project, click the button to obtain data across domains in the Index page of the Web project, and open the browser console to view the request result. The following result will appear in the console:

The console prompts us that the cross-domain request is blocked and that the CORS header information is true, so we can configure CORS to support cross-domain access by going to WebAPI.

So now we can add Microsoft.AspNet.WebApi.Cors through Nuget in the WebAPI project, and then configure the EnableCors method of HttpConfiguration in the WebApiConfig.cs file. The specific operations 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) {/ / WebAPI configuration and Service EnableCrossSiteRequests (config); / / WebAPI routing config.MapHttpAttributeRoutes () Config.Routes.MapHttpRoute (name: "DefaultApi", routeTemplate: "api/ {controller} / {action} / {id}", defaults: new {id = RouteParameter.Optional}); / / clear all serialization formats config.Formatters.Clear (); / / add serializer config.Formatters.Add (new JsonMediaTypeFormatter ()) in Json format } / allow cross-domain calls / private static void EnableCrossSiteRequests (HttpConfiguration config) {/ / No restrictions on all request sources var cors = new EnableCorsAttribute (origins: "*", headers: "*", methods: "*"); config.EnableCors (cors);}

Now, we re-generate the WebAPI project and run it, and then click the button "Cross-domain get data" in the page http://localhost:31521/Index.aspx. Through the console of firebug, we can see that the cross-domain loading of the data is successful, as follows:

The above is all the contents of the article "sample Analysis of supporting Ajax Cross-domain access to ASP.NET Web Api 2". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report