原文:http://www.cnblogs.com/chenxizhang/p/3821703.html
一、配置webconfig
問題描述
當跨域(cross domain)調用ASP.NET MVC或者ASP.NET Web API編寫的服務時,會發生無法訪問的情況。
重現方式
public class TestController : ApiController { // GET api/test public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/test/5 public string Get(int id) { return "value"; } // POST api/test public void Post([FromBody]string value) { } // PUT api/test/5 public void Put(int id, [FromBody]string value) { } // DELETE api/test/5 public void Delete(int id) { } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.10.2.min.js"></script> <script> $(function () { var url = "http://localhost:49136/api/test"; $ajax({ type: "GET", contentType: "application/json", url: url, datatype: 'json', success: function (result) { alert(result); } }); }); </script> </head> </html>
3.在瀏覽器中打開這個網頁,我們會發現如下的錯誤(405:Method Not Allowed)
【備注】同樣的情況,也發生在ASP.NET MVC中。某些時候,MVC也可以直接用來開發服務,與WebAPI相比各有優缺點。下面是一個利用MVC開發的服務的例子
public class HomeController : Controller { // GET: /Home/ public ActionResult Index() { return Json(new { Id = 1 }, JsonRequestBehavior.AllowGet); } }
原因分析
跨域問題僅僅發生在Javascript發起AJAX調用,或者Silverlight發起服務調用時,其根本原因是因為瀏覽器對於這兩種請求,所給予的權限是較低的,通常只允許調用本域中的資源,除非目標服務器明確地告知它允許跨域調用。
所以,跨域的問題雖然是由於瀏覽器的行為產生出來的,但解決的方法卻是在服務端。因為不可能要求所有客戶端降低安全性。
解決方案
針對ASP.NET MVC和ASP.NET Web API兩種項目類型,我做了一些研究,確定下面的方案是可行的。
1 MVC
針對ASP.NET MVC,只需要在web.config中添加如下的內容即可
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
2 Web API
針對ASP.NET Web API,除了上面這樣的設置,還需要添加一個特殊的設計,就是為每個APIController添加一個OPTIONS的方法,但無需返回任何東西。
public string Options()
{
return null; // HTTP 200 response with empty body
}
錯誤1 重復配置
WebApiConfig配置,網上有推薦此配置方法
// Web API 配置和服務 var cors = new EnableCorsAttribute("*", "*", "*");//添加跨域支持代碼 config.EnableCors(cors);//添加跨域支持代碼s
但web.config也配置后會出現如下問題,是因為重復配置 問題
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed
但去掉web.config的配置無法跨域,所以不要配置WebApiConfig
錯誤2 憑據模式為“include”
當請求的憑據模式為“include”時,響應中的標頭不能是通配符“*”
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
場景:使用MVC特性
[EnableCors(origins: "*", headers: *", methods: "*")]
改為
[EnableCors(origins: "*", headers: "Content-Type", methods: "*")]
文章: https://cloud.tencent.com/developer/ask/123697
=========================================================================================
以下是瞎扯
最近用webapi寫了個小項目,基於.NET 4.0,遇到這個跨域的問題,就被坑死,這里要先感謝下博主
有問題肯定找度娘,顯示發現用JSONP來實現,找了以下比較經典的文章
http://www.cnblogs.com/Kummy/p/3767269.html
http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html
看了好多文章,js和服務端都要做一些麻煩的配置,最后發現一個更大的坑:只支持get。頓時,淚奔,我用的是高大上的post。
http://diaosbook.com/Post/2013/12/27/tips-for-aspnet-webapi-cors
在該文發現可以用Microsoft.AspNet.WebApi.Cors, 注意:只支持4.5以上(偷偷淚奔)
需要學習cors的,可以看看artech 的系列爽文,哈哈,共8章
http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-01.html
其他不說了,認真看完,對跨域有較深的認識
二、間接請求
web.config中配置解決跨域問題,在實際中無法跨域
臨時解決方法:在客戶端使用中間層做代理
以下是php網站間接調用
<?php error_reporting(0); $destURL="http://xx.cn/api/Post"; $queryString=$_SERVER['QUERY_STRING']; if($_SERVER['REQUEST_METHOD']=='GET'){ $url=$destURL.$queryString; echo file_get_contents($url); } else{ $url=$destURL.$queryString; $context = array(); $context['http'] = array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($_POST) ); echo file_get_contents($url, false, stream_context_create($context)); } ?>
另外,使用jsonp測試也本地實現了,回頭再寫
三、客戶端請求Header
原文:https://blog.csdn.net/eternity_zzy/article/details/79664234
---------------------
// 為所有的ajax請求都會加上這個請求頭 $(document).ajaxSend(function (event, xhr) { xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8") ; xhr.setRequestHeader("val", "val") ; }); //局部 第一種 $('xxx').ajax({ //... beforeSend:function(jqXHR,options){ jqXHR.setRequestHeader("Content-Type", "application/json;charset=utf-8") ; jqXHR.setRequestHeader("Authorization", "Authorization") ; } //... }) ; //局部 第二種 如JWT $('xxx').ajax({ //... headers:{ "Content-Type": "application/json;charset=utf-8", "Authorization":"Bearer xxxxxxxx", } //... }) ;
注意:修改請求頭時,headers中的設置會覆蓋beforeSend中的設置(意味着beforeSend先執行,所以被后面的headers覆蓋)
后台接收
public void (@RequestHeader("Content-Type") String cType, @RequestHeader("Authorizationr") String a){}