Project development decided to use ANGULAR2 for front-end separation development, I was responsible for the development of the backend services, initially selected the Web API for development. Cross-domain access is supported through API middleware + filters across domain access. After a period of development, the notification needs to be ported to the MVC4 project to publish ANGULAR2 and discard the API, but pre-development still requires separation of development.
You want to continue to use middleware and filters to manipulate and limit the action in MVC, but it's not possible to try it out. There are several points in the main question.
- The API's processing pipeline and MVC's processing pipeline are two completely different things, so the encoding and methods used in the API are not reusable.
- There are other ways to resolve the issue of the options request in a JavaScript cross-domain request. (The data shows that JavaScript does not allow cross-domain requests for security reasons.) )
- Workarounds and Steps
- To handle the cross-domain content in the HTTP response header, I used the following additions in <system.webServer> in Web. config.
1 <Httpprotocol>2 <customheaders>3 <Addname= "Access-control-allow-origin"value="*" />4 <Addname= "Access-control-allow-headers"value= "Content-type" />5 <Addname= "Access-control-allow-methods"value= "GET, POST, PUT, DELETE, OPTIONS" />6 </customheaders>7 </Httpprotocol>
(Value of other headers: Origin, No-cache, X-requested-with, If-modified-since, Pragma, last-modified, Cache-control, Expires, Content-type, X-e4m-with, Authorizatio)
(Please increase or decrease according to the actual needs!) )
- Processing HTTP request Zhong Options request content
When a cross-domain request is made, an options request is triggered first, depending on the content in the header of the response and the return status, to determine whether a formal get, post, and so on are required. However, in real-world development, it is not possible to duplicate the action to handle HTTP request characteristics (attribute).
1 [httpoptions]2 [HttpPost]3public ActionResult Index ()4 {5 return View (); 6 }
My approach is to pass on all options requests in Global.asax. To tell the client to request it normally.
1 voidapplication_endrequest ()2 {3 if( This. Request.HttpMethod.ToUpper (). Equals ("OPTIONS"))4 {5 This. Response.Status ="OK";6 This. Response.statuscode = $;7 This. Response.statusdescription ="OK";8 This. Response.substatuscode = $;9 }Ten}
A GET request, two requests under cross-domain operations, one options, one get. Where a GET request executes as mentioned earlier, it is triggered according to the status of the options request.
- Artech's book, "The Secret of the ASP MVC5 framework"
- "Resolving cross-domain request issues with ASP." MR.XYZ's Blog
Cross-domain access to ASP. NET MVC in ANGULAR2