JQuery. ajax cross-origin request webapi sets headers solution, jquery. ajaxwebapi
To solve the problem of cross-origin service calling and set headers, you must set the response header on the server side, correctly respond to the options request, and correctly set the headers information to be set on the JavaScript side.
1. Step 1: Set the response header on the server side and set the following settings in web. config of webapi:
<System. webServer>
2. the second step is to understand the "pre-request" of IE chrome and other browsers when cross-origin requests are required to set Headers custom parameters. If cross-origin requests and headers are configured, all requests must be completed in two steps!
A Step 1: Send the pre-request OPTIONS request. In this case, the server needs to respond to the OPTIONS request. Generally, 202 is used to respond without returning any content. (The person who can see this manuscript does not believe that you cannot process an options request in the background.) The options request can be processed in the permission interceptor.
/// <Summary> /// permission interceptor /// </summary> public class ApiAuthorizeAttribute: AuthorizeAttribute {public override void OnAuthorization (HttpActionContext actionContext) {if (actionContext. request. method = HttpMethod. options) {actionContext. response = actionContext. request. createResponse (HttpStatusCode. accepted); return ;}}}
B Step 2: After the server accepted Step 1 request, the browser automatically executes Step 2 to send the real request.
Client code:
$ ("# BtnSumit "). click (function () {var Ticket = $. cookie ("token"); var model = {id: 1}; $. ajax ({type: "POST", url: "http: // localhost: 65312/api/products/FindProductById", data: JSON. stringify (model), contentType: "application/json; charset = UTF-8", dataType: "json", beforeSend: function (xhr) {// before sending an ajax request, add the verification information xhr to the http head. setRequestHeader ("token", Ticket); // before the request is initiated, append the token in the header}, success: function (data, status) {if (data. statuscode = "401") {alert (data. msg);} else {alert (JSON. stringify (data) }}, // error: function (XMLHttpRequest, textStatus, errorThrown) {// alert (XMLHttpRequest. status); // alert (XMLHttpRequest. readyState); // alert (textStatus); //}, complete: function (){}});});
The above section describes jQuery. the ajax cross-origin request webapi sets the headers solution. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!