问题描述
我试图按照在步骤
有我的RESTful API(使用ASP.NET WebAPI2实现)跨起源请求工作(CORS启用)。它不工作,除非我修改web.config。
我安装的WebAPI一个Cors依赖性:
安装包Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api
然后在我的 App_Start
我已经得到了类 WebApiConfig
如下:
公共静态类WebApiConfig
{
公共静态无效的注册(HttpConfiguration配置)
{
变种corsAttr =新EnableCorsAttribute(*,*,*);
config.EnableCors(corsAttr); VAR constraintsResolver =新DefaultInlineConstraintResolver(); constraintsResolver.ConstraintMap.Add(apiVersionConstraint的typeof(ApiVersionConstraint));
config.MapHttpAttributeRoutes(constraintsResolver);
config.Services.Replace(typeof运算(IHttpControllerSelector),新NamespaceHttpControllerSelector(配置));
//config.EnableSystemDiagnosticsTracing();
config.Services.Replace(typeof运算(ITraceWriter),新SimpleTraceWriter(WebContainerManager.Get< ILogManager>()));
config.Services.Add(typeof运算(IExceptionLogger),新SimpleExceptionLogger(WebContainerManager.Get< ILogManager>()));
config.Services.Replace(typeof运算(IExceptionHandler),新GlobalExceptionHandler());
}
}
但在那之后我运行应用程序,我要求与小提琴手像一个资源:
的人
并在响应中我看不到HTTP头,我应该看到,例如:
-
访问控制允许的方法:POST,PUT,DELETE,GET,OPTIONS
-
访问控制允许来源:*
我丢失了一些步骤?我曾尝试与控制器上的以下标注:
[EnableCors(来源:http://example.com,标题:*,方法:*)]
同样的结果,没有启用CORS。
不过,如果我在我的web.config中添加以下内容(甚至没有安装AspNet.WebApi.Cors依赖)工作原理:
< system.webServer>< httpProtocol>
<! - 这些头是很重要的与CORS作品 - >
<! -
< customHeaders>
<添加名称=访问控制允许来源VALUE =*/>
<添加名称=访问控制允许的方法VALUE =POST,PUT,DELETE,GET,OPTIONS/>
<添加名称=访问控制 - 允许 - 头VALUE =内容类型,接受,产地,X-要求,随着,授权名/>
<添加名称=访问控制允许的凭据VALUE =真/>
< / customHeaders>
- >
< / httpProtocol>
<&处理GT;
<! - 这些处理器是重要的,WEB API与GET,HEAD,POST,PUT工作,DELETE和CORS - >
<! - <清除NAME =WebDAV的/>
<添加名称=ExtensionlessUrlHandler - 集成 - 4.0PATH =*。动词=GET,HEAD,POST,PUT,DELETETYPE =System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
<清除NAME =ExtensionlessUrlHandler - 集成 - 4.0/>
<清除NAME =OPTIONSVerbHandler/>
<清除NAME =TRACEVerbHandler/>
<添加名称=ExtensionlessUrlHandler - 集成 - 4.0PATH =*。动词=*类型=System.Web.Handlers.TransferRequestHandlerpreCondition =integratedMode,runtimeVersionv4.0/>
- >
< /处理器>
任何帮助将是非常美联社preciated!
感谢您。
我创建了一个削减的演示项目适合你。
- 源代码:
- API链接:
您可以尝试从当地的提琴手以上的 API链接,查看标题。这里有一个解释。
这样做只是叫 WebApiConfig
。这只不过code组织。
公共类WebApiApplication:System.Web.HttpApplication
{
保护无效的Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
你这里的关键方法是 EnableCrossSiteRequests
方法。这是全部,你需要做的。在 EnableCorsAttribute
是的。
公共静态类WebApiConfig
{
公共静态无效的注册(HttpConfiguration配置)
{
EnableCrossSiteRequests(配置);
AddRoutes(配置);
} 私有静态无效AddRoutes(HttpConfiguration配置)
{
config.Routes.MapHttpRoute(
名称:默认,
routeTemplate:API / {}控制器/
);
} 私有静态无效EnableCrossSiteRequests(HttpConfiguration配置)
{
VAR CORS =新EnableCorsAttribute(
来源:*,
标题:*,
方法: *);
config.EnableCors(CORS);
}
}
的获取
方法接收 EnableCors
属性,我们全球应用。在另一个
方法覆盖全局 EnableCors
。
公共类ValuesController:ApiController
{
//获取API /值
公共IEnumerable的<串GT;得到()
{
返回新的String [] {
这是一个CORS的回应。
它可以从任何来源。
};
} //获取API /价值/其他
[HTTPGET]
[EnableCors(来源:http://www.bigfont.ca,标题:*,方法:*)]
公共IEnumerable的<串GT;另一个()
{
返回新的String [] {
这是一个CORS的回应。
它只能从两个来源:
1. www.bigfont.ca
2.同样的起源。
};
}
}
您不需要添加任何特殊到web.config中。其实,这是演示的web.config看起来像 - 它是空的。
。 <?XML版本=1.0编码=UTF-8&GT?;
<结构>
< /结构>
演示
VAR URL =https://cors-webapi.azurewebsites.net/api /值\r
\r
$获得(URL,功能(数据){\r
的console.log(我们预计这一成功。);\r
的console.log(数据);\r
});\r
\r
VAR URL =https://cors-webapi.azurewebsites.net/api/values/another\r
\r
$获得(URL,功能(数据){\r
的console.log(数据);\r
})失败(函数(XHR,状态,文本){\r
的console.log(我们预计这个失败。);\r
的console.log(状态);\r
});
\r
&LT;脚本src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>$c$c>$p$p>\r
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工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!