Resolve a Cross-domain call service and set headers The primary solution is to set up the response header through the server side, respond correctly to the options request, and properly set the headers information that the JavaScript side needs to set.
1. The first step is to set up the response header in the Webapi Web.config to make the following settings
2. The second part of the understanding of IE Chrome and other browsers for Cross-domain requests and requirements to set headers custom parameters when the "pre-request" is if you encounter Cross-domain and set the headers request, all requests need two steps to complete!
A First step: Send A Pre-request OPTIONS request. At this point the server side needs to respond to the options request generally use a 202 response to do not return any content information. (who can see this manuscript, I don't believe you can't handle a options request) the options request can be handled 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 Two: The server accepted the first step, the browser automatically executes the second step 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) {
/////////////////////////////////
Xhr.setrequestheader ("token", Ticket);//Request prior to the header additional 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 () {
}
});
The above is a small set to introduce Jquery.ajax Cross-domain request Webapi Settings Headers solution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!