- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在设置一个 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-preview3 中,我们无法对每条消息使用 fetch 选项,该选项是全局的
WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
WebAssemblyHttpMessageHandler
已被删除。使用的 HttpMessageHanlder
是来自 WebAssembly.Net.Http
的 WebAssembly.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>();
}
在 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
包。
将 WebAssemblyHttpMessageHandler
替换为 BlazorHttpMessageHandler
关于c# - Blazor 请求被 PHP API 上的 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689421/
我刚开始学习JSP技术,遇到了瓶颈。 如何从 JSP 声明 block ? 这不起作用: ... 服务器说没有“out”。 U: 我确实知道如何使用返回字符串的方法重写代码,但是有没有办法在 ?
在一个字段中,我想设置一个具有自定义过滤器的自定义分析器-着眼于词干-因此,“闪存卡”和“闪存卡”的词根相同,因此返回的结果相同 当我运行以下查询时,我的命中率很高,但是“闪存卡”和“闪存卡”各自返回
快速提问。 我有一个通过 PInvoke 使用 native DLL 的应用程序,这个 DLL 可能会调用 PostQuitMessage()。 如何避免? (因为我的应用程序不应该关闭) 我试过 A
一些给定的 HTML 文章,例如: Content 与一些基本的 Jquery 结合使用,例如: $(".some_
我正在构建一个灯箱相册。当第一个图像加载时,CSS 转换起作用。当加载后的每个图像都没有。任何想法为什么?加载第一张之后的照片,但没有过渡。 Image.prototype.load = functi
这个问题在这里已经有了答案: Disable recent tasks button on Android 5.0 (2 个答案) 关闭 2 年前。 我知道这个问题之前在这里被问过 Android
我是 Objective-C 的新手,我只是想弄清楚我是否可以使用 block 或选择器作为 UIAlertView 的 UIAlertViewDelegate 参数 - 哪个更合适? 我已经尝试了以
我是 Linux (UNIX) 套接字下套接字编程的新手。我在 Internet 上找到了以下代码,用于为每个连接生成一个线程的 tcp 服务器。但是它不起作用。accept() 函数立即返回,不等待
recv()库函数手册页提到: It returns the number of bytes received. It normally returns any data available, up
我有一个用于其他项目的共享 ts 库。在这个库中有被同一个库的其他资源使用的资源。该库的结构分为 components/*、interfaces/*、services/* 等目录。在每个目录的根目录中
我想在同一行中一个接一个地显示我的 ListView ,但 ListView 显示每个新行中的每个项目。我怎样才能防止换行显示。以便它显示为段落 ListView.builder( shr
我有一个包含数千行的表格。 import React from "react" import { useSelector } from "react-redux"; import { useEffec
假设我通常希望收到关于代码中不完整模式的警告,但有时我知道某个函数的模式不完整,我知道这很好。 是still true GHC 的警告粒度是每个模块的,并且没有办法更改有关特定功能或定义的警告? 最佳
我的网络应用程序发送浏览器通知,我知道如何检查通知的浏览器权限,以及如果未授予权限,如何请求权限。 但是,即使用户授予我的站点发送通知的权限,她可能仍然无法收到通知,因为它们 might be dis
我有 Xcode 3.2.1,并且喜欢使用它,但是当我编辑文本中带有超链接的文件时(例如,带有引用的注释:# see http://example.com)Xcode 将文本变成可点击的超链接。尝试编
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许在 Stack Overflow 上提出有关通用计算硬件和软件的问题。您可以编辑问题,使其成为
我有一个在 MY_Controller 中运行的 acl。如果权限被拒绝,那么此刻,我只是执行 redirect('denied') - 这是一个非常基本的 Controller ,它加载一个非常基本
我一直很好奇尝试从 Chrome 切换到 Firefox Quantum,但是对于 Web 开发遇到了一个我无法轻松解决的主要障碍——它正在缓存我的本地主机文件,因此当我尝试在本地主机加载各种 emb
这真的让我很兴奋!在任何时候,我都会参与多个项目。当我退出Xcode时,下次打开Xcode时,我前一天的所有项目都会自动一一打开。 经常我最终编辑错误的文件,AHHHHHHHHHHH!我可以阻止这种行
我的Wiki上有500个左右的Spambot和大约5个实际注册用户。我已经使用nuke删除了他们的页面,但是他们一直在重新发布。我已经使用reCaptcha控制了spambot的注册。现在,我只需要一
我是一名优秀的程序员,十分优秀!