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

}

}

相关推荐
唐青枫1 小时前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
专注仿真7 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
我是苏苏10 小时前
Agent 开发实战 :C#实现语义检索!向量数据库Qdrant的下载安装及调试步骤
c#·ai编程
光泽雨11 小时前
IEnumerable<T> 详细讲解
c#·c
Lost of 程序猿11 小时前
.NET 10 船端单机部署与离线升级实战:从闪退事故到无感回滚
c#·asp.net·.net
淡海水12 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
唐青枫1 天前
对象到底住在哪里?C#.NET 托管堆从分配、GC 到内存排查
c#·.net
fogota1 天前
Emoji与Segoe MDL2 Assets的比较
c#·wpf
灸木1 天前
C# 多线程与异步
c#