我有两个VS项目:一个公开MVC5控制器,另一个是有角度的客户端。我希望有角度的客户端能够查询控制器。我阅读了许多主题,并尝试了以下方法:
<system.webServer> <httpProtocol> <customHeaders> <clear /> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> <system.webServer>
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*"); base.OnActionExecuting(filterContext); } }
app.factory("CORSInterceptor", [ function() { return { request: function(config) { config.headers["Access-Control-Allow-Origin"] = "*"; config.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"; config.headers["Access-Control-Allow-Headers"] = "Content-Type"; config.headers["Access-Control-Request-Headers"] = "X-Requested-With, accept, content-type"; return config; } }; } ]); app.config(["$httpProvider", function ($httpProvider) { $httpProvider.interceptors.push("CORSInterceptor"); }]);
根据Firebug,这导致以下请求:
OPTIONS //Login/Connect HTTP/1.1 Host: localhost:49815 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Origin: http://localhost:50739 Access-Control-Request-Method: POST Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,content-type Connection: keep-alive Pragma: no-cache Cache-Control: no-cache
以及以下响应:
HTTP/1.1 200 OK Allow: OPTIONS, TRACE, GET, HEAD, POST Server: Microsoft-IIS/10.0 Public: OPTIONS, TRACE, GET, HEAD, POST X-SourceFiles: =?UTF-8?B?RDpcVEZTXElVV2ViXEdhcE5ldFNlcnZlclxBU1BTZXJ2aWNlc1xMb2dpblxDb25uZWN0?= Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, OPTIONS Access-Control-Allow-Headers: * Access-Control-Request-Headers: X-Requested-With, accept, content-type Date: Tue, 01 Sep 2015 13:05:23 GMT Content-Length: 0
而且,Firefox使用以下消息阻止请求:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49815//Login/Connect. (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
通常,我阅读的线程暗示了一些不必要的配置步骤,这造成了混乱。实际上非常简单…
为了将跨站点请求从有角度的客户端发送到ASP控制器的简单目的:
<system.webServer> <httpProtocol> <customHeaders> <clear /> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type"/> </customHeaders> </httpProtocol> </system.webServer>