解决方案
不提倡跨域的post请求。
0.jquery中ajax的跨域方案jsonp
.ashx代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace KB.DSN.Web.API.Tokens
{
/// <summary>
/// Summary description for Get
/// </summary>
public class Get : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
setresponsecontext(context);
var token = KB.DSN.BusinessAccess.UniqueCommunicationCode.GenerateUniqueCommunicationCode();
var outputobject = new
{
Head = new Models.KBJsonHeadResponse(),
Body = new { Token = token }
};
var outputjsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(outputobject);
context.Response.Write(context.Request.QueryString["callback"]+"("+outputjsonstring+")");
}
private void setresponsecontext(HttpContext context)
{
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = "application/json";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
html页面
function getToken_jsonp(){
$.ajax({
url: "http://192.168.0.111/api/tokens/get.ashx",
type: "get",
dataType: "jsonp",
jsonp: "callback",
async: false,
contentType: "application/json",
success: function(data){
//alert("getToken success");
$("#token").text($.toJSON(data));
//console.log(data);
},
error:function(){
alert("getToken fail");
}
});
}
jsonp只支持GET请求,不支持POST请求,就算你写了POST,它会自动转换为GET请求,把你的data放在querystring中。
1.修改web.config文件
整个应用都支持跨域的请求。
web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
html page
function addContact() {
var contact = new Object();
contact.FirstName = $("#firstName").attr("value");
contact.LastName = $("#lastName").attr("value");
contact.PhoneNo = $("#phoneNo").attr("value");
contact.EmailAddress = $("#emailAddress").attr("value");
$.ajax({
url: "http://localhost:10401/api/contacts/AddContact.ashx",
type: "POST",
dataType: "json",
data: $.toJSON(contact),
success: function () { loadAllContacts(); }
});
}
这种方式不能设置contentType: "application/json",否则会提示
"Request header field Content-Type is not allowed by Access-Control-Allow-Headers."
去掉ajax中的contentType设置就可以了!
想要设置contentType也可以,需要将web.config文件中的
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
修改为
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
在II6中web.config不支持system.webServer配置节,所以需要在IIS中设置httprequestheader。将web.config文件中的自定义头加入IIS的设置中。
FindContact.ashx
/// <summary>
/// Summary description for FindContact
/// </summary>