jQuery. ajax cross domain request webapi setup headers solution

  • 2021-07-09 06:59:08
  • OfStack

The main solution to cross-domain calling services and setting headers needs to set response header on the server side, respond to options requests correctly, and set headers information on the JavaScript side correctly.

1. Step 1 Set the response header on the server, and make the following settings on web. config of webapi


<system.webServer>
<httpProtocol>
<!-- Cross-domain configuration starts -->
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" /><!-- Support full domain name access, which is unsafe. After deployment, it needs to be fixed and limited to the client website address -->
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /><!-- Supported http  Action -->
<add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With,token" /><!-- Response header   Please add it according to your own needs   There is a new addition here token This headers-->
<add name="Access-Control-Request-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /><!-- Allow the requested http  Action -->
</customHeaders>
<!-- End of cross-domain configuration -->
</httpProtocol>

2. Part 2 understands that the "pre-request" when browsers such as IE and chrome request cross-domain requests and require setting Headers custom parameters is that if cross-domain requests and setting headers are encountered, all requests need to be completed in two steps!

A Step 1: Send a pre-request OPTIONS request. At this point, the server needs to respond to the OPTIONS request, so you don't need to return any content information by using 202 response. (For those who can see this manuscript, I don't believe that you can't handle an options request in the background.) options request can be processed in the permission interceptor


/// <summary>
///  Privilege 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: Server accepted Step 1 After the 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) {
// // Send ajax Request prior to http Adj. head Add verification information to it 
xhr.setRequestHeader("token", Ticket); //  Attach to the header before the request is initiated token
},
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 () {
}
});
});

Related articles: