CORS configuration is used to implement jQuery cross-origin access to WebApi and MVC.
In js ajax operations, cross-origin access is not allowed by default. We can use CORS configuration to implement the simplest cross-origin access. This method is used to control cross-origin access on the server.
I. Write server code
Create an ASP. net mvc/WebApi project, and create Api methods and MVC Action methods respectively:
The WebApi method is as follows:
Public class ValuesController: ApiController {// GET api/values public IEnumerable <string> Get () {return new string [] {"value1", "value2 "};} // GET api/values/5 public string Get (int id) {return "value";} // POST api/values public string Post ([FromBody] MyModel value, string name) {TextHelper. writeLineAppend (@ "D: \ my log. txt", string. format ("API name: {0}", name); return string. format ("API Hello, {0}", name) ;}// PUT api/values/5 public void Put (int id, [FromBody] string value) {}// DELETE api/values/5 public void Delete (int id ){}}View Code
The MVC Action method is as follows:
Public class HomeController: Controller {public ActionResult Index () {return View ();} public string MyTest (string name1, MyModel m) {TextHelper. writeLineAppend (@ "D: \ my log. txt", string. format ("MVC: {0}", name1); return string. format ("MVC Hello, {0}", name1 );}}View Code 2. Compile client Code
Create another ASP. net mvc project, reference the jQuery file, and access the Api or MVC method in POST mode on the page.
@ {Layout = null ;}<! DOCTYPE html> In this case, the following error is prompted:
Cross-source requests are blocked: The same-source policy prohibits reading at http: // 192.168.0.12: 8013/home/mytest? Name1 = % E5 % 8D % 8E % E6 % B6 % 9B Remote resource. (Cause: the CORS header lacks 'access-Control-Allow-origin ').
3. Add CORS configuration on the server
To solve JS cross-origin problems, configure CORS in the configuration file of the server project:
<System. webServer> ...... In this way, JavaScript cross-origin access can be performed.