问题描述
我尝试按照 $ b $的步骤操作b让我的RESTful API(使用ASP.NET WebAPI2实现)使用跨源请求(CORS已启用)。它不工作,除非我修改web.config。
我安装了WebApi Cors依赖:
install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api
然后在我的 App_Start
我有类 WebApiConfig
如下:
public static class WebApiConfig
{
public static void注册(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute(*,*,*);
config.EnableCors(corsAttr);
var constraintsResolver = new DefaultInlineConstraintResolver();
constraintsResolver.ConstraintMap.Add(apiVersionConstraint,typeof(ApiVersionConstraint));
config.MapHttpAttributeRoutes(constraintsResolver);
config.Services.Replace(typeof(IHttpControllerSelector),new NamespaceHttpControllerSelector(config));
//config.EnableSystemDiagnosticsTracing();
config.Services.Replace(typeof(ITraceWriter),new SimpleTraceWriter(WebContainerManager.Get< ILogManager>()));
config.Services.Add(typeof(IExceptionLogger),new SimpleExceptionLogger(WebContainerManager.Get< ILogManager>()));
config.Services.Replace(typeof(IExceptionHandler),new GlobalExceptionHandler());
}
}
但是在运行应用程序后,资源与Fiddler类似:
并在响应中我看不到HTTP标头,我应该看到,例如:
-
访问控制允许-Methods:POST,PUT,DELETE,GET,OPTIONS
-
访问控制允许原产地:*
我缺少一些步骤吗?我试过在控制器上的以下注释:
[EnableCors(origin:http://example.com,headers: *,方法:*)]
结果相同,未启用CORS。
$ b b
但是,如果我在我的web.config中添加以下内容(甚至没有安装AspNet.WebApi.Cors依赖项):
< system.webServer>
< httpProtocol>
<! - 这些标题重要工作CORS - >
<! -
< customHeaders>
< add name =Access-Control-Allow-Originvalue =*/>
< add name =Access-Control-Allow-Methodsvalue =POST,PUT,DELETE,GET,OPTIONS/>
< add name =Access-Control-Allow-Headersvalue =content-Type,accept,origin,X-Requested-With,Authorization,name/>
< add name =Access-Control-Allow-Credentialsvalue =true/>
< / customHeaders>
- >。
< / httpProtocol>
< handlers>
<! - 这些处理程序对于WEB API来说是重要的,GET,HEAD,POST,PUT,DELETE和CORS - >
<! -
< remove name =WebDAV/>
< add name =ExtensionlessUrlHandler-Integrated-4.0path =*。 verb =GET,HEAD,POST,PUT,DELETEtype =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
< remove name =ExtensionlessUrlHandler-Integrated-4.0/>
< remove name =OPTIONSVerbHandler/>
< remove name =TRACEVerbHandler/>
< add name =ExtensionlessUrlHandler-Integrated-4.0path =*。 verb =*type =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
- >
< / handlers>
!
谢谢。
您可以尝试上面的 API Link 从本地Fiddler查看标题。这是一个解释。
这一切都是调用 WebApiConfig
。它只是代码组织。
public class WebApiApplication:System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
这里的关键方法是 EnableCrossSiteRequests
方法。这是全部,您需要做。 EnableCorsAttribute
是一个。
public static class WebApiConfig
{
public static void注册(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
AddRoutes(config);
}
private static void AddRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name:Default,
routeTemplate:api / {controller} /
);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
originins:*,
headers:*,
methods:*);
config.EnableCors(cors);
}
}
Get
方法接收我们全局应用的 EnableCors
属性。 另一个
方法覆盖全局 EnableCors
。
public class ValuesController:ApiController
{
// GET api / values
public IEnumerable< string> Get()
{
return new string [] {
这是一个CORS响应。,
它从任何原点开始工作。
};
}
// GET api / values / another
[HttpGet]
[EnableCors(originins:http://www.bigfont.ca,headers :*,methods:*)]
public IEnumerable< string>另一个()
{
return new string [] {
这是一个CORS响应,
它只能从两个来源起作用:,
1. www.bigfont.ca,
2.同一起源。
};
}
}
您不需要添加任何特殊的web.config。事实上,这是演示的web.config看起来像 - 它是空的。
<?xml version =1.0 encoding =utf-8?>
< configuration>
< / configuration>
演示
var url =https://cors-webapi.azurewebsites.net/api/values\"$.get(url,function(data){console.log ); console.log(data);}); var url =https://cors-webapi.azurewebsites.net/api/values/another\"$.get(url,function(数据){console.log(data);})。fail(function(xhr,status,text){console.log(我们期望这会失败。 code> < script src =https://ajax.googleapis。 com / ajax / libs / jquery / 2.1.1 / jquery.min.js>< / script>
>
I tried to follow the steps at http://enable-cors.org/server_aspnet.htmlto have my RESTful API (implemented with ASP.NET WebAPI2) work with cross origin requests (CORS Enabled). It's not working unless I modify the web.config.
I installed WebApi Cors dependency:
install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api
Then in my App_Start
I've got the class WebApiConfig
as follows:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
var constraintsResolver = new DefaultInlineConstraintResolver();
constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
config.MapHttpAttributeRoutes(constraintsResolver);
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
//config.EnableSystemDiagnosticsTracing();
config.Services.Replace(typeof(ITraceWriter), new SimpleTraceWriter(WebContainerManager.Get<ILogManager>()));
config.Services.Add(typeof(IExceptionLogger), new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>()));
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}
}
but after that I run the application, I request a resource with Fiddler like:http://localhost:51589/api/v1/personsand in the response I cannot see the HTTP headers that I should see such as:
Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS
Access-Control-Allow-Origin: *
Am I missing some step? I have tried with the following annotation on the controller:
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
Same result, no CORS enabled.
However, if I add the following in my web.config (without even installing the AspNet.WebApi.Cors dependency) it works:
<system.webServer>
<httpProtocol>
<!-- THESE HEADERS ARE IMPORTANT TO WORK WITH CORS -->
<!--
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
-->
</httpProtocol>
<handlers>
<!-- THESE HANDLERS ARE IMPORTANT FOR WEB API TO WORK WITH GET,HEAD,POST,PUT,DELETE and CORS-->
<!--
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<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>
Any help would be much appreciated!
Thank you.
I've created a pared-down demo project for you.
- Source: https://github.com/bigfont/webapi-cors
- Api Link: https://cors-webapi.azurewebsites.net/api/values
You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.
Global.ascx
All this does is call the WebApiConfig
. It's nothing but code organization.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
WebApiConfig.cs
The key method for your here is the EnableCrossSiteRequests
method. This is all that you need to do. The EnableCorsAttribute
is a globally scoped CORS attribute.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
AddRoutes(config);
}
private static void AddRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/"
);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
}
}
Values Controller
The Get
method receives the EnableCors
attribute that we applied globally. The Another
method overrides the global EnableCors
.
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] {
"This is a CORS response.",
"It works from any origin."
};
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] {
"This is a CORS response. ",
"It works only from two origins: ",
"1. www.bigfont.ca ",
"2. the same origin."
};
}
}
Web.config
You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
Demo
var url = "https://cors-webapi.azurewebsites.net/api/values"
$.get(url, function(data) {
console.log("We expect this to succeed.");
console.log(data);
});
var url = "https://cors-webapi.azurewebsites.net/api/values/another"
$.get(url, function(data) {
console.log(data);
}).fail(function(xhr, status, text) {
console.log("We expect this to fail.");
console.log(status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于Asp.Net WebApi2启用CORS不能使用AspNet.WebApi.Cors 5.2.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!