惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
博客园 - 叶小钗
F
Fortinet All Blogs
GbyAI
GbyAI
Martin Fowler
Martin Fowler
博客园 - 聂微东
I
InfoQ
B
Blog
IT之家
IT之家
美团技术团队
L
LangChain Blog
小众软件
小众软件
C
Check Point Blog
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
Last Week in AI
Last Week in AI
A
About on SuperTechFans
博客园 - Franky
P
Proofpoint News Feed
罗磊的独立博客
月光博客
月光博客
V
Visual Studio Blog
MyScale Blog
MyScale Blog

博客园 - fenix

IISExpress 开放局域网访问 sql窗口函数 Sql分页语句 常用SQL 数据库导出结构的sql 单进程运行 MahApps.Metro样式 iis7 添加Mime sudoku Geometric paths,mini language Accessing WMF metadata with C# 标点符号 摘抄 temp C# deep copy 数独 简单对称加密 ICommand ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications
WebAPI post 跨域调用及坑
fenix · 2016-01-13 · via 博客园 - fenix

nuget中安装Microsoft ASP.NET Web API Cors相关的两个包
EnableCors可以在方法 类上用EnableCorsAttibute设置
也可以在WebApiConfig的Register方法中,直接config.EnableCors()

IIS的设置,在web.config中
<system.webServer>中

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
</customHeaders>
</httpProtocol>

WebAPI方法第一个参数使用[FromBody],post多个值,需要定义成一个对象,当成一个[FromBody]参数

1.

$(document).ready(function () {
var ecParams = {
"pID": 0,
"eItemIDs": ["01", "42"],
"startTime": "2016/01/10",
"endTime": "2016/01/11"
};
var prm = JSON.stringify(ecParams);
$.ajax(
{
//url: "http://xxx.xxx.xxx.xxx/xxxAPI/api/EItemDatas/getEItemData",
url: "../api/EItemDatas/getEItemData",
type: "post",
dataType: "json",
contentType: "application/json", 
data: prm
success: function (data) {
alert(data);
},
error: function (XHR, text, err) {
alert(text);
}
}
);
});

2.

$(document).ready(function () {
var ecParams = {
"pID": 0,
"eItemIDs": ["01", "42"],
"startTime": "2016/01/10",
"endTime": "2016/01/11"
};
//var prm = JSON.stringify(ecParams);
$.ajax(
{
url: "http://xxx.xxx.xxx.xxx/xxxAPI/api/EItemDatas/getEItemData",
//url: "../api/EItemDatas/getEItemData",
type: "post",
dataType: "json",
//contentType: "application/json", 
data: ecParams,
success: function (data) {
alert(data);
},
error: function (XHR, text, err) {
alert(text);
}
}
);
});


如上两段代码,第1段可以正常使用
第2段也可以正常使用,但是如果在第1段中调用跨域的接口会出现error,原因暂未知
ecParams的各个key跟getEItemData方法的参数类属性名完全一致