我已经按照通常的步骤在web.api中启用了cors,但在Chrome和Firefox中获得了对OPTIONS请求的404响应我获得了Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mydomain.com/api/1/widgets. This can be fixed by moving the resource to the same domain or enabling CORS.
在我的WebApiConfig.cs中,我得到了:
var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(enableCorsAttribute);
我还尝试将EnableCors
属性添加到特定控制器或操作中,并且都具有相同的结果。
我还在web.config中添加了以下内容:
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
...
这是我的javascript:
$.ajax({
url: 'https://api.mydomain.com/api/1/widgets',
type: "GET",
headers: {
Accept: "text/html; charset=utf-8",
Authorization: 'Bearer ???????????????????????????????'
}
});
但Chrome的响应为404,而#34; Cross-Origin请求被阻止&#34;在Firefox中。
以下是我的Chrome开发人员工具栏中失败请求的详细信息:
Remote Address:??.???.???.???:443
Request URL:https://api.mydomain.com/api/1/widgets
Request Method:OPTIONS
Status Code:404 Not Found
请求
OPTIONS /api/1/widgets HTTP/1.1
Host: api.mydomain.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://myotherdomain.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://myotherdomain.com/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6
响应
HTTP/1.1 404 Not Found
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Origin: http://myotherdomain.com
Access-Control-Allow-Credentials: true
X-AspNetMvc-Version: 5.0
X-UA-Compatible: IE=edge,chrome=1
X-Frame-Options: SAMEORIGIN
Cache-conrol: no-store
Date: Thu, 28 Aug 2014 16:00:28 GMT
Content-Length: 341
我错过了什么?
答案 0 :(得分:7)
如果其他人遇到同样的问题,这个问题是因为我们在IIS中使用了Microsoft的优秀UrlScan。
UrlScan有AllowVerbs部分和DenyVerbs部分。确保允许选项动词。
答案 1 :(得分:0)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:3000", "*", "*");
config.EnableCors(corsAttr);
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = new GuidConstraint() });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
config.Routes.MapHttpRoute("DefaultApiOptions", "Api/{controller}", new { action = "Options" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) });
}
}
最后一行可以解决.Net WebApi的问题