The previous article wrote about cross-domain issues with WEBAPI, in which the method only solves the cross-domain problem of a simple request, rather than a simple request.
to figure out cors rules What types of cross-domain resource requests are divided into simple request categories That requires an extra understanding of the meaning of several names (HTTP) party method (simple Method) (please head (Simple Hader) " and" Custom request header (Author Request header/custom request header) " /span>
The Cors specification treats the three HTTP methods of, and post as simple HTTP Methods and requests headers Accept, Accept-language, Content-language and Content-type with application/x-www-form-urlencoded, Multipart/form-data, and Text/plain headers are called simple request headers.
In short, a simple request is an HTTP request with a simple method that contains only a simple request header, and the other requests are simple requests. The signature parameters required for cross-domain signatures as mentioned in this article are added in the custom header of the HTTP request (if the signature information is included in the parameters of the processing function, it appears that the interface signature is very low).
Cross-domain is actually said that the browser of the same origin policy on the JavaScript script Ajax request Some restrictions, blocking the application of the data requested by the script operation, rather than blocking the request sent and the data received, if you use the Packet Capture tool to view the network data, you can obviously see the request sent, and the normal data return of the interface. But why does the browser not handle the data properly? This is because the browser needs to be authorized by the resource provider to distribute the resource to the consumer (that is, the JavaScript script), and Ajax adds an "Origin" header to the headers at the request of the cross-domain resource, the value of which is the domain where the request is currently originating. Therefore, to solve the cross-domain problem of a simple request, only the value of Origin in the request message needs to be processed, the response to the authorized domain is added a response header "Access-control-allow-origin", general response to the authorization domain header " Access-control-allow-origin "value is set to" * ". Instead of a simple request, the cross-domain invocation process differs from the simple message invocation process, where the browser uses a "preflight" mechanism to complete a cross-domain resource request for a non-simple request when sending a non-trivial message.The so-called preflight mechanism is that the browser sends a pre-check request before sending a real cross-domain resource request (Preflightrequest).The preflight request is a0PTIONS SquareThe request of the lawThisis a request that does not contain a principalUseThe header associated with the user credential will also be excluded. Some of the secondary authorization information based on a real resource request is included in the response header of this preflight request. In addition to the Origin of the site where the request page resides"Outside the headerSuch asThe following is a sample of two typical request headers.
Access-control-request-method: The cross-domain resource request takesHTTP PartyMethod.
Access-control-request-headers: A list of custom headers that are carried with cross-domain resource requests.
The provider of the resource receives the preflight request and verifies the authorization based on the relevant header it provides, including determining whether the requesting site is trustworthyToand requests to adoptHTTP PartyThe method and custom headers are allowed. If the preflight request does not pass authorization verification, the resource provider typically returns a response with a status of "400,bad Reuqest" (also customizable to return message messages, as in this article). Conversely, a status of 200 is returned.,ok " response (can also customize return message messages) "Access-control-allow-origin " " Span class= "FONTSTYLE0" > outside the header , pre- The response to the check request also has the following 3 typical header.
Access-control-allow-methodhttp Party Access-control-allow-headers: Cross
access-control-max-Age: The time (in seconds) that the browser can cache the response results , which allows browsers to avoid frequent sending of preflight requests.
If the preflight request meets the following three conditions, the browser considers that the cross-domain resource request that will be sent later is authorized
by request "Origin " header indicates that the source site must exist in" Access-control-allow-origin " The response header identifies the site in the list.
preflight request "Access-control-request-headers " Header store header names are all in the response header" Access-control-allow-headers " The list of headers represented.
preflight request "Access-control-request-method " header represents the request method within the list indicated by the preflight request Response message" Access-control-allow-methods ".  &NBSP
so above: to complete a cross-domain request for non-simple messages, The pre-check request must be properly answered on the server side, and when the preflight request is received, it will need to be added "Access-control-allow-origin " in the response message.
above is for cross-domain, The pre-check mechanism and the description of its solution, followed by the actual processing method
(1) Cross-Domain support: Add a Filter property to the controller and override the OnActionExecuted method to add a custom header to the response message.
(2) Preflight message response: Because the General API Controller does not implement the options method, and the pre-test message request method is the options, so we need to implement the option method. As for each controller more than one usually do not use the Options method, written in there ugly, this is the system architecture to consider the problem, here we only say specific problems specific solutions.
(3) interface Signature Verification: Add a Filter property to the controller to carry out its own validation logic for the custom message, and this will be played at random.
Cross-domain pre-check message support code:
<summary>///Add cross-domain support///</summary> public class Enablecors:actionfilterattribute { <summary>///operation mark///</summary> private bool flag {get; Set }///<summary>///default constructor true: Turn on Cross domain false: Turn off cross-domain support///</summary>//<param Nam E= "Para" ></param> public enablecors (bool para) {Flag = para; }///<summary>/////</summary>//<param name= "Actionexecutedcont Ext "></param> public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext) {base. OnActionExecuted (ActionExecutedContext); if (Flag! = true) return; if (Actionexecutedcontext.response = = null) return; if (ActionExecutedContext.Response.Headers.Contains ("Access-control-allow-origin")) {Actionexec UtedcontexT.response.headers.remove ("Access-control-allow-origin"); } if (ActionExecutedContext.Response.Headers.Contains ("Access-control-allow-method")) { ActionExecutedContext.Response.Headers.Remove ("Access-control-allow-method"); } if (ActionExecutedContext.Response.Headers.Contains ("Access-control-allow-headers")) { ActionExecutedContext.Response.Headers.Remove ("Access-control-allow-headers"); } actionExecutedContext.Response.Headers.Add ("Access-control-allow-origin", "*"); ACTIONEXECUTEDCONTEXT.RESPONSE.HEADERS.ADD ("Access-control-allow-methods", "GET, POST, PUT, DELETE, OPTIONS"); ACTIONEXECUTEDCONTEXT.RESPONSE.HEADERS.ADD ("Access-control-allow-headers", "Content-type,timestamp,parameter, Randnum "); } }
Interface Signature Code:
<summary> ///Interface Signature Properties ///</summary> [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)] public class Apiauthorization:authorizationfilterattribute { public override void Onauthorization (Httpactioncontext actioncontext) { base. Onauthorization (actioncontext); if (ActionContext.Request.Method = = httpmethod.options) return;//supports cross-domain custom header requests (preflight mechanism) //todo here is the code for the interface signature, Can be taken from the definition of the head for processing, the signature through the direct return, otherwise the actioncontext.response is assigned, indicating that the operation after the signature failed Actioncontext.response = ActionContext.Request.CreateResponse (Httpstatuscode.forbidden, New Checkresult () {Result = false, Message = "Access Denied! "}); } }
&NBSP;
<summary>///Basic controller/// </summary> [DataType (Apidatatype.json)] [Enablecors (True) ] [Description ("API base Controller")] [apiauthorization] public class Apibasecontroller:apicontroller { //<summary>///To support Ajax cross-domain preflight mechanism ///</summary> public void Options () { } }
Through the above steps to complete the cross-domain pre-detection message response, interface signature. The actual running effect is as follows:
First I send a non-trivial message operation, I actually caught the two packets through fiddler, the first is the above mentioned pre-inspection message, the second is to contain all of our custom message headers to achieve our True cross-domain resource request message.
And the information of the pre-test request message and the reply message (the format is as above):
Cross-domain resource request messages and their response messages are as follows (note our custom headers for interface signatures):
Here is a normal cross-domain operation, and the signature verification failed message, is also a pre-test message, a formal message
A brief analysis of cross-domain signature of ASP Webapi