一、用visual studio 2015 創建一個 web api 應用程序。記住這是一個 web api 應用。jquery
二、新建一個web api 。web
三、用C#訪問,代碼以下:[沒有問題,返回正確] json
var requestJson = JsonConvert.SerializeObject(args); HttpContent httpContent = new StringContent(requestJson); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var httpClient = new HttpClient(); var responseJson = httpClient.PostAsync("http://webml01.dxqas.com/datacenter/api/affiliate/queryproduct", httpContent) .Result.Content.ReadAsStringAsync().Result;
但若是用jquery去調用web api 則會出現:api
<Error><Message>The requested resource does not support http method 'OPTIONS'.</Message></Error>
解決方法以下:
一、編寫一個 web api 的基類如 BaseApi.cs 繼承自 ApiController 在BaseApi.cs中添加以下代碼
public HttpResponseMessage Options() { return new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; }
二、在 web.config 中<system.webServer> 節點中添加以下配置app
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>spa
完成以上兩部,再用jquery去調用。則不出再報錯。但F12看請求時會發現有兩個請求產生。code