Cross-origin access to ASP. net mvc in Angular2, angular2mvc
Project Development decides to use angular2 for frontend and backend separate development. I am responsible for backend service development. At first, I chose web api for development. Cross-origin access is supported through API middleware + filter. After a development period, the notification needs to be transplanted to the MVC4 project and angular2 is released and the API is abandoned. However, the early development stage still requires separate development.
I want to continue to use the middleware and filter methods to operate and limit the Action in MVC, but after trying, I found that it would not work. The main problems are as follows.
- Solution and steps
- To process cross-origin content in the HTTP response header, add the following content in <system. webServer> of web. config.
1
(Other headers values: Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, x-E4M-With (Authorizatio)
(Increase or decrease based on actual needs !)
- Process the content of the http request zhong options request
In a cross-origin request, an options request is triggered first. Based on the content in the response header and the returned status, determine whether to perform a formal GET or POST request. However, in actual development, it is impossible to repeatedly mark the action to process the http request attribute ).
1 [HttpOptions]2 [HttpPost]3 public ActionResult Index()4 {5 return View();6 }
My solution is to manually pass all options requests in Global. asax. To tell the client that the request is normal.
1 void Application_EndRequest() 2 { 3 if (this.Request.HttpMethod.ToUpper().Equals("OPTIONS")) 4 { 5 this.Response.Status = "200 OK"; 6 this.Response.StatusCode = 200; 7 this.Response.StatusDescription = "OK"; 8 this.Response.SubStatusCode = 200; 9 }10 }
For a GET request, two requests, one OPTIONS and one GET, are performed in a cross-origin operation. The execution of the GET request is triggered according to the status of the OPTIONS request, as mentioned above.