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

}

}

相关推荐
爱吃奥利奥_wen30 分钟前
面向对象三板斧:封装、继承、多态,到底在“装“什么、“承“什么、“变“什么?
开发语言·经验分享·c#
wflynn12 小时前
GitHub 今日推荐|SCSKiller:游戏着色器预编译消除卡顿
开源·c#·github·nvidia·amd·directx12
疯狂的维修1 天前
关于用C#写电机起保停控制
开发语言·c#
用户788477316341 天前
门店核销闭环:小程序扫码 + .NET 幂等接口 + WPF 看板,一天能跑通
微信小程序·c#
samble1 天前
从零搭建灌装监控系统(十三):报警系统设计,生命周期与通知
c#·wpf·mvvm·modbus·工业控制
miofly2 天前
GitHub 今日推荐|SCSKiller:游戏着色器预编译消除卡顿
开源·c#·github
周杰伦fans2 天前
8GB显存下模型量化实战指南
人工智能·后端·c#
samble2 天前
从零搭建灌装监控系统(十二):配置系统,原子写入与容错
c#·wpf·mvvm·modbus·工业控制
流形填表2 天前
题库去重实战:基于题干指纹的重复题清理
开发语言·c#
开开心心就好3 天前
以图搜图找重复图片,本地工具离线就能用
javascript·智能手机·ffmpeg·c#·ocr·word·音视频