gpt4 book ai didi

c# - Blazor 请求被 PHP API 上的 CORS 策略阻止

转载 作者:行者123 更新时间:2023-12-01 20:00:11 24 4
gpt4 key购买 nike

我正在设置一个 PHP API 和一个基于客户端 Blazor 的网页。但由于某种原因,CORS 被触发,我的登录过程或对我的 PHP 页面的任何请求都会导致 CORS 错误。

我开始使用 C# 控制台应用程序和 Blazor 应用程序测试我的 PHP API,我尝试在没有任何数据库访问权限的情况下使用来测试功能。 Blazor 目前正在运行 Preview 9。PHP 版本是 5.3.8。理论上我可以更新它,但其他几个活跃的项目正在其上运行,并且我没有任何测试环境。 MySQL 版本 5.5.24。

首先,我认为这可能是因为我在本地计算机上运行它,所以我将其推送到 PHP 和 MySQL 也运行的网站上。我仍然遇到了这个 CORS 错误。

我仍在测试这个,所以我尝试将其设置为允许任何来源。在此之前我没有任何关于 CORS 的经验。很确定我应该能够在我访问的每个允许 CORS 的文件中添加 PHP 代码,但由于它们都应该位于同一个网站上,所以我认为 CORS 甚至不应该相关?

PHP 代码:

function cors() {

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

exit(0);
}

echo "You have CORS!";
}
cors();

使用注入(inject)的 HttpClient 的 C# 代码:

var resp = await Http.GetStringAsync(link);

我得到的错误是:

Access to fetch at 'https://titsam.dk/ntbusit/busitapi/requestLoginToken.php' from origin 'https://www.titsam.dk' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我希望得到的响应是我使用的链接会返回一个用于登录的 token ,就像它为我的 API 所做的那样。

是否是因为其正在运行的客户端可能会触发 CORS?但这似乎并不能解释为什么我不能让它允许一切。

更新:我在 OnInitializedAsync 中的 C# 代码:

link = API_RequestLoginTokenEndPoint;

Http.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "basic:testuser:testpass");

var requestMessage = new HttpRequestMessage(HttpMethod.Get, link);

requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = "include"
};

var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();

output = responseBody + " " + responseStatusCode;

更新2:它终于起作用了。我链接的 C# 代码是 Agua From Mars 建议的解决方案,它解决了将 SendAsync 与 HttpRequestMessage 结合使用并向其添加 Fetch 属性包括凭据的问题。另一种选择是将这一行添加到启动中:

WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;

然后我可以继续做我开始做的事情,使用 GetStringAsync,因为它成为默认值。等待 Http.GetStringAsync(API_RequestLoginTokenEndPoint);

因此,Agua From Mars 建议的所有解决方案都有效。但我遇到了一个浏览器问题,即使解决了 CORS 问题,它仍然以某种方式将其保留在缓存中,所以看起来好像什么都没有改变。一些代码更改会显示不同的结果,但我猜 CORS 部分仍然存在。通过 Chrome,它可以帮助打开新的 Pane 或窗口。在我的 Opera 浏览器中,这还不够,我必须关闭打开站点的所有 Pane ,以确保清除缓存,然后打开一个新窗口或 Pane ,该站点在 Opera 中也能正常工作。我已经在两个浏览器中尝试使用 ctrl-F5 和 Shift-F5 让它们清除缓存。这并没有改变任何东西。

我希望这能帮助其他人避免在此类问题上花费 2-3 天的时间。

最佳答案

更新3.1-预览版3

在 3.1-preview3 中,我们无法对每条消息使用 fetch 选项,该选项是全局的

WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;

WebAssemblyHttpMessageHandler 已被删除。使用的 HttpMessageHanlder 是来自 WebAssembly.Net.HttpWebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler,但不包含 WebAssembly。 Net.Http 在您的依赖项中,否则应用程序将无法启动。

如果你想使用HttpClientFactory,你可以这样实现:

public class CustomDelegationHandler : DelegatingHandler
{
private readonly IUserStore _userStore;
private readonly HttpMessageHandler _innerHanler;
private readonly MethodInfo _method;

public CustomDelegationHandler(IUserStore userStore, HttpMessageHandler innerHanler)
{
_userStore = userStore ?? throw new ArgumentNullException(nameof(userStore));
_innerHanler = innerHanler ?? throw new ArgumentNullException(nameof(innerHanler));
var type = innerHanler.GetType();
_method = type.GetMethod("SendAsync", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod) ?? throw new InvalidOperationException("Cannot get SendAsync method");
WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Authorization = new AuthenticationHeaderValue(_userStore.AuthenticationScheme, _userStore.AccessToken);
return _method.Invoke(_innerHanler, new object[] { request, cancellationToken }) as Task<HttpResponseMessage>;
}
}

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient(p =>
{
var wasmHttpMessageHandlerType = Assembly.Load("WebAssembly.Net.Http")
.GetType("WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler");
var constructor = wasmHttpMessageHandlerType.GetConstructor(Array.Empty<Type>());
return constructor.Invoke(Array.Empty<object>()) as HttpMessageHandler;
})
.AddTransient<CustomDelegationHandler>()
.AddHttpClient("MyApiHttpClientName")
.AddHttpMessageHandler<CustonDelegationHandler>();
}

3.0 -> 3.1-预览2

在 Blazor 客户端,您需要告诉 Fetch API发送凭据(cookie 和授权 header )。

Blazor 文档中有描述 Cross-origin resource sharing (CORS)

        requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = FetchCredentialsOption.Include
};

例如:

@using System.Net.Http
@using System.Net.Http.Headers
@inject HttpClient Http

@code {
private async Task PostRequest()
{
Http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "{OAUTH TOKEN}");

var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://localhost:10000/api/TodoItems"),
Content =
new StringContent(
@"{""name"":""A New Todo Item"",""isComplete"":false}")
};

requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue(
"application/json");

requestMessage.Content.Headers.TryAddWithoutValidation(
"x-custom-header", "value");

requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = FetchCredentialsOption.Include
};

var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
}
}

您可以使用 WebAssemblyHttpMessageHandlerOptions.DefaultCredentials 静态属性全局设置此选项。

或者您可以实现一个 DelegatingHandler 并使用 HttpClientFactory 在 DI 中设置它:

    public class CustomWebAssemblyHttpMessageHandler : WebAssemblyHttpMessageHandler
{
internal new Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken);
}
}

public class CustomDelegationHandler : DelegatingHandler
{
private readonly CustomWebAssemblyHttpMessageHandler _innerHandler;

public CustomDelegationHandler(CustomWebAssemblyHttpMessageHandler innerHandler)
{
_innerHandler = innerHandler ?? throw new ArgumentNullException(nameof(innerHandler));
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = "include"
};
return _innerHandler.SendAsync(request, cancellationToken);
}
}

Setup.ConfigureServices

services.AddTransient<CustomWebAssemblyHttpMessageHandler>()
.AddTransient<WebAssemblyHttpMessageHandler>()
.AddTransient<CustomDelegationHandler>()
.AddHttpClient(httpClientName)
.AddHttpMessageHandler<CustomDelegationHandler>();

然后,您可以使用 IHttpClientFactory.CreateClient(httpClientName) 为您的 API 创建一个 HttpClient

要使用IHttpClientFactory,您需要安装Microsoft.Extensions.Http包。

3.0-preview3 => 3.0-preview9

WebAssemblyHttpMessageHandler 替换为 BlazorHttpMessageHandler

关于c# - Blazor 请求被 PHP API 上的 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689421/

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