我有两个VS项目:一个暴露MVC5控制器,另一个是角度客户端.我希望角度客户端能够查询控制器.
我读了很多线程,尝试了以下内容:
我读了很多线程,尝试了以下内容:
>我在服务器的web配置中添加了这个:
<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,POST X-SourceFiles: =?UTF-8?B?RDpcVEZTXElVV2vixEdhcE5ldFNlcnZlclxBU1BTZXJ2aWNlc1xMb2dpblxDb25uZWN0?= Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET,OPTIONS Access-Control-Allow-Headers: * Access-Control-Request-Headers: X-Requested-With,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控制器的简单目的:
>不需要角度拦截器.
>服务器端不需要自定义过滤器.
>唯一的强制修改是将它添加到服务器的web.config中
<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>
原文地址:https://www.jb51.cc/angularjs/140816.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。