调用 Webapi 跨域
先讲一下,web和client各自调用webapi的post和get实例
Get方式
[HttpGet]
public dynamic Test(string a)
{
return a+"---";
}
web调用
$.ajax({
type: "Get",
url: '../api/MyController/Test',
dataType: "json",
data:"123",
success: function (d) {
}
})
Client调用
static async void APIGet(string url)
{
//创建HttpClient(注意传入HttpClientHandler)
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
//await异步等待回应
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
Post方式
[HttpPost]
public dynamic Test([FromBody]string data)
{
return data+"---";
}
web调用
var data = { "": "123" };
$.ajax({
type: "Post",
url: "../api/MyController/Test",
dataType: "json",
data: data,
success: function (d) {
}
});
client调用
public static async Task<string> APIPost(string url, string data)
{
string result = string.Empty;
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"", data}//键名必须为空
});
var response = await http.PostAsync(url, content);
response.EnsureSuccessStatusCode();
result = await response.Content.ReadAsStringAsync();
}
return result;
}
方法1 配置web.config
对于跨域,比较简单的是配置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, PUT, DELETE" />
</customHeaders>
</httpProtocol>