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");

}

}

相关推荐
何以解忧唯有撸码7 小时前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手17 小时前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库1 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc1 天前
C# 发展历史
开发语言·c#
kyle~2 天前
C# --- 反射
开发语言·c#
暴走约伯3 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316343 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船4 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261354 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船4 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug