|
Problem description When a cross-domain call ASP.NET MVC or a service written ASP.NET Web API, it becomes inaccessible. Reproduction method - Use a template to create a simplest ASP.NET Web API project, debug it to make sure it works
- Create another project with only one HTML page and make an AJAX call
- Open this page in your browser and you will find the following error (405: Method Not Allowed)
Note: The same situation occurs in ASP.NET MVC. In some cases, MVC can also be used directly to develop services, which has its own advantages and disadvantages compared to WebAPI. Below is an example of a service developed using MVC
Cause analysis The fundamental reason for the cross-domain problem is that the browser has low privileges on both requests and usually only allows calls to resources in the local domain, unless the target server explicitly tells it that cross-domain calls are allowed. Therefore, although the cross-domain problem is caused by the behavior of the browser, the solution is on the server side. Because it is not possible to require all clients to reduce security.
solution For both ASP.NET MVC and ASP.NET Web API project types, I did some research and determined that the following scenario is feasible. For ASP.NET MVC, you only need to add the following content to the web.config
For ASP.NET Web APIs, in addition to the above settings, a special design needs to be added, which is to add an OPTIONS method for each API Controller, but without returning anything. public string Options() { return null; // HTTP 200 response with empty body }
Note: This function can also be done with some research, and it may be better to design it as a filter.
|