http://blog.csdn.net/hanjun0612/article/details/51799996
先讲一下,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)
- {
-
- var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
-
- using (var http = new HttpClient(handler))
- {
-
- var response = await http.GetAsync(url);
-
- response.EnsureSuccessStatusCode();
-
-
- 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>
方法2 设置 CORS
http://www.cnblogs.com/landeanfen/p/5177176.html