No'Access-Control-Allow-Origin' header is present on the requested resource. Cross-domain problem solving

Create a .net webapi program, create an index.html page under the project folder to request the webapi interface, the code is as follows:

webapi code:

 

index code:

 

 

In the browser, you can see that the request is successful and hello is returned

 At this time, if you create a new page outside the webapi project folder, the home.html page, and also send an ajax request to request webapi, the code is as follows:

At this time, the browser reported an error and a cross-domain request occurred. This is the security mechanism of the browser. By default, programs are not allowed to access resources in other servers. 

This is just that the browser intercepted the request. If you use the tool to simulate the request, you can access the api interface normally. Use ApiPost to access the interface below:

 

 If you want to use a browser (front end) to access the api interface, the cross-domain problem can also be solved. The solution is to reference the package Microsoft.AspNet.WebApi.Cors in the api program and install this package in NuGet:

 

Then add configuration information to the project's WebApiConfig.cs file to allow cross-domain requests.

 

It is also necessary to add websites and methods that are allowed to be accessed across domains in the controller:

The asterisk (*) here means that all methods can be requested across domains.

 

After the configuration information is added, start the project, refresh the home.html page, and request webapi. At this time, the browser no longer reports cross-domain errors. The interface call is successful and returns the result:

 

In summary, to solve the cross-domain problem of webapi browser access, three steps are required:

1. Reference package in WebApi project: Microsoft.AspNet.WebApi.Cors.

2. Add configuration information to the project file WebApiConfig.cs to allow the project to be requested across domains.

3. Configure information in a specific controller (Controller), allowing which methods of the controller can be requested across domains.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/109263391