gpt4 book ai didi

.net - ASP.NET WebApi - 为多个来源启用 CORS

转载 作者:行者123 更新时间:2023-12-05 06:41:35 24 4
gpt4 key购买 nike

我一直在尝试为我的 API 的多个来源启用 CORS,但没有成功。

这是我所做的。

创建了 CORS 策略

 [AttributeUsage(AttributeTargets.All, AllowMultiple =false, Inherited =true)]
public class TCCorsPolicyProvider : Attribute, ICorsPolicyProvider
{
private CorsPolicy _policy;

public TCCorsPolicyProvider()
{
_policy = new CorsPolicy
{
SupportsCredentials = true
};
string[] allowedOrigins = "john.doe,ava.wise".Split(',');
string[] allowedMethods = "GET,POST,PUT,OPTIONS".Split(',');
string[] allowedHeaders = "Content-Type,Origin,Authorization,Accept".Split(',');
// Add allowed origins.
foreach (string origin in allowedOrigins)
_policy.Origins.Add(origin);
foreach (string method in allowedMethods)
_policy.Methods.Add(method);
foreach (string header in allowedHeaders)
_policy.Headers.Add(header);
}

public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(_policy);
}
}

创建工厂

public class TCCorsPolicyProviderFactory : ICorsPolicyProviderFactory
{
ICorsPolicyProvider _provider;
public TCCorsPolicyProviderFactory()
{
_provider = new TCCorsPolicyProvider();
}
public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
{
return _provider;
}
}

在 WebApiConfig.cs 类中启用 Cors

config.SetCorsPolicyProviderFactory(new TCCorsPolicyProviderFactory());
config.EnableCors();

确保在 Global.asax Application_Start 中进行了适当的注册

 GlobalConfiguration.Configure(WebApiConfig.Register);

当上述方法不起作用时,我什至手动将策略属性应用到我的基本 Controller ,所有其他 Controller 都继承自该 Controller

[TCCorsPolicyProvider]
public class BaseApiController : ApiController
{
public string IpAddress
{
get { return ContextHelper.GetIpAddress(); }
}

private bool _disposed;
protected virtual void Dispose(bool disposing, Action disposeAction)
{
if (!_disposed)
{
if (disposing)
{
disposeAction();
}
}
_disposed = true;
}
}

但我收到以下错误(从 Angular 调用 Api)

XMLHttpRequest cannot load hqidwtcdwa01/api/localizations/reloadCache. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'ava.wise' is therefore not allowed access. The response had HTTP status code 401.

hqidwtcdwa01 是目的地,ava.wise 是起点。

到目前为止,我发现 xmlhttp 响应中的 http 响应 header 不包含 Access-Control-Allow-Origin。但是,当我使用 HttpCient 时,我可以看到 header 。 HttpClient Response

Postman Response

最佳答案

我相信 cors 理论上允许多个来源,但实际上不允许。对于我的站点,我创建了一个新的 CORS 属性并根据传入返回一个允许的来源,这比使用 *

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = false)]
public class GlobalEnableCorsAttribute :


Attribute, ICorsPolicyProvider
{
public Boolean SupportsCredentials = true;
public CorsHandler handle = new CorsHandler();
public async Task<CorsPolicy> GetCorsPolicyAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var corsRequestContext = request.GetCorsRequestContext();
var originRequested = corsRequestContext.Origin;


string approvedOrigin = handle.approveCorsOrigin(originRequested);

if(!string.IsNullOrEmpty(approvedOrigin))
{
// Grant CORS request
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
SupportsCredentials = true
};

// add headers
policy.Headers.Add("content-type");
policy.Headers.Add("withcredentials");
policy.Headers.Add("Access-Control-Allow-Headers");
policy.Headers.Add("Access-Control-Allow-Origin");
policy.Headers.Add("Origin");
policy.Headers.Add("Accept");
policy.Headers.Add("X-Requested-With");
policy.Headers.Add("Access-Control-Request-Method");
policy.Headers.Add("Access - Control - Request - Headers");


policy.Origins.Add(approvedOrigin);
return policy;
}
else
{
// Reject CORS request
return null;
}
}



}

来源搜索从服务器配置值中获取允许的来源

 public class CorsHandler
{
public string approveCorsOrigin(string providedOrigin)
{
// load list of web.config origins
string fullList = Properties.Settings.Default.CORSOriginPermittedSite;

if (!string.IsNullOrEmpty(fullList))
{
string[] originArray = fullList.Split(new char[]{ ','}, StringSplitOptions.RemoveEmptyEntries);

foreach(string approvedOrigin in originArray)
{
if (providedOrigin.Trim() == approvedOrigin.Trim())
{
return providedOrigin;
}
}
}
return null;
}
}

用法如下

 public static void Register(HttpConfiguration config)
{
if (Properties.Settings.Default.CORSOriginPermittedSite != null && !string.IsNullOrWhiteSpace(Properties.Settings.Default.CORSOriginPermittedSite))
{
var cors = new GlobalEnableCorsAttribute();
config.EnableCors(cors);
}
}

最后,此代码针对 webapi 设置,但应该具有可比性,并且您还(如果使用类似的)需要使飞行前处理同源搜索..

关于.net - ASP.NET WebApi - 为多个来源启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com