我正在通过HttpContext.Current
对象直接编写ASP.NET MVC的请求头,但这些头信息没有被发送到浏览器... 有什么想法是什么原因?如果我通过web.config添加标头,则仅获取标头。对我来说,这不起作用,因为我需要允许多个域访问Access-Control-Allow-Origin
。
我尝试使用以下代码直接将标头写入HttpContext.Current
。
context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World " + DateTime.Now.ToString());
我能运行 hello world,但是没有头文件。我尝试使用
Thinktecture.IdentityModel.Http.Cors.WebApi
,但是仍然无法得到任何结果。我检查并重复检查了我的代码确保它符合教程1。我已经在 Web.config 中配置了头文件,并尝试了 Thinktecture 但只有当 Access-Control-Allow-Origin
在 Web.config 中时才能获得头文件,但我仍然在 Chrome/FF 中遇到错误。似乎头文件只在 OPTIONS 请求中发送,但我不确定。Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,ga;q=0.6,pt-BR;q=0.4,pt;q=0.2
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:GET
Authorization:Negotiate REDACTED
Cache-Control:max-age=0
Connection:keep-alive
Host:bpapi.domain.com
Origin:http://dev-02
Referer:http://dev-02/_Layouts/PAR/NewParItem.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Persistent-Auth: false
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: http://dev-02
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
WWW-Authenticate: Negotiate REDACTED
Date: Sat, 06 Apr 2013 00:35:31 GMT
Content-Length: 0
这里有一个web.config as a pastebin,以免混淆问题。WebDAV未安装。
public class CorsConfig
{
public static void RegisterCors(HttpConfiguration httpConfig)
{
WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
corsConfig.RegisterGlobal(httpConfig);
corsConfig
.ForResources(new string[] { "Industries", "Projects" })
.ForOrigins(new string[] { "http://dev-01", "http://dev-02" })
.AllowAll();
}
}
以下是 Thinktecture 代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
RegisterCors(MvcCorsConfiguration.Configuration);
}
private void RegisterCors(MvcCorsConfiguration corsConfig)
{
corsConfig
.ForResources(new string[] {"Industries", "Projects" })
.ForOrigins(new string[] { "http://dev-01", "http://dev-02" })
.AllowAll();
}
更新于2013/04/09: context.Response.AppendHeader(...)
和context.Response.AddHeader(...)
都没有任何效果。如果浏览器得到了JSONP,Chrome和FF似乎无论是否允许来源头都可以正常工作,所以我的项目至少是有效的。我还尝试过<remove name="OPTIONSVerbHandler"/>
,但没有成功。我将把MVC应用程序部署到新服务器上,看看它是否是特定机器本地化的问题。