ajax跨域请求

前端

$.ajax({

type: 'post',

crossDomain: true,

url: 'http://localhost:10771/RMBase/API/APIHandler.ashx',

data:{ "UserName": "aabbc","Pwd":"123" },

contentType: "application/json", // POST时必须

xhrFields: {

'Access-Control-Allow-Origin': '*'

},

success: function (data, textStatus, jqXHR) {

alert(data);

alert(jqXHR.getAllResponseHeaders());

//console.log("getAllResponseHeaders:" + jqXHR.getAllResponseHeaders());

// console.dir(jqXHR);

// Backbone.history.navigate("#booklist", true);

}

});

C# 端

一、放在Global.asax 中

protected void Application_BeginRequest()

{

// 允许跨域访问的源,生产环境建议替换为具体域名

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");

// 处理预检请求

if ("OPTIONS" == HttpContext.Current..Request.RequestType)

{

context.Response.StatusCode = 204;

context.Response.End();

}

}

}

二、每次请求是设置Header

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

context.Response.AddHeader("Access-Control-Allow-Origin", "*");

context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");

if ("OPTIONS" == context.Request.RequestType)

{

context.Response.StatusCode = 204;

context.Response.End();

}

else

{

using (var reader = new StreamReader(context.Request.InputStream))

{

string json = reader.ReadToEnd();

}

context.Response.Write("Hello World");

}

}

相关推荐
He BianGu20 小时前
【笔记】C# 中BindingFlags的详细作用
笔记·c#
?abc!20 小时前
(贪心)621. 任务调度器
java·前端·c#
开开心心就好1 天前
电脑小说阅读器,支持朗读和自定义皮肤
服务器·开发语言·javascript·算法·pdf·c#·音视频
淡海水1 天前
07-06-源码-.NET Core GC的极致优化技术
unity·架构·c#·.netcore·gc·1024程序员节
万化冥合1 天前
怎么批量把 Word 转 PDF?
python·pdf·c#·word
淡海水2 天前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
吴可可1232 天前
C#调用摄像头拍照的三种API方案
c#
Msir_Modern2 天前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
星之擎2 天前
Task 很优雅的取消方式是什么?C# 里面。
开发语言·c#
czhc11400756632 天前
一周概念复盘:预热、漂移与门禁
c#