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

推荐订阅源

IT之家
IT之家
Engineering at Meta
Engineering at Meta
腾讯CDC
宝玉的分享
宝玉的分享
H
Help Net Security
I
InfoQ
博客园 - Franky
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
博客园_首页
美团技术团队
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
The Cloudflare Blog
博客园 - 司徒正美
Vercel News
Vercel News
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方法的参数类属性名完全一致