【发布时间】:2021-02-12 15:09:54
【问题描述】:
我正在尝试做与在 JavaScript 代码中但在 C# 中所做的相同的事情。最终结果是我想从 C# 代码中自动执行此任务,我将在其中手动创建这些文件。此代码用于网页以实现其目标:
第一个函数是将文件放在缓冲区中的一个位置。
function FileIOU(file: File, backendUrl: string, dispatch: any) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = async () => {
await fetch(`${ backendUrl}/ www.FileIOU?filename =${file.name}`, {
method: 'POST',
body: reader.result,
mode: 'no-cors',
}).then(resolve).catch (err => {
console.log('FileIOU', err);
dispatch(consoleOutputAction('Failed to send file: ' + file.name, 'error'));
reject();
});
};
reader.readAsArrayBuffer(file);
第二个函数调用这个文件在站点上运行。
fetch(`${props.configuration.backendUrl}/www.RunFile?name=${e.currentTarget.id}`);
我模仿这个的方式是:
public async static Task PostFile(string file)
{
byte[] byteArray = new byte[] { };
File.WriteAllBytes(file, byteArray);
var fileName = Path.GetFileName(file);
var byteContent = new ByteArrayContent(byteArray);
var response = await Client.PostAsync(
"https://localhost/simulatorweb/www.FileIOU?filename="+$"{fileName}"
, byteContent);
}
第二部分是:
public async static Task RunFile(string fileName)
{
var response = await Client.PostAsync(
$"https://localhost/www.RunFile?name="+$"{fileName}", null);
}
一旦我调用了这个函数,我就会得到响应405,尽管这可能看起来我需要根据 JavaScript 在 C# 中设置“no-cors”,尽管我不确定如何执行此操作。但可能还有其他问题,我没有看到。
{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Fri, 30 Oct 2020 06:15:42 GMT
Connection: keep-alive
Vary: Origin
Accept-Ranges: bytes
Content-Length: 0
Allow: GET
Allow: HEAD
Allow: OPTIONS
}}
【问题讨论】:
-
请注意:您当前正在向文件中写入
0字节(使用File.WriteAllBytes),因为您初始化了一个空字节数组,因此您还将一个 0 字节的数组发布到您的服务器。你想要的是使用var byteArray = File.ReadAllBytes(file) -
CORS 是一项浏览器功能。
HttpClient不使用也不遵守 CORS。 -
你的 JavaScript 版本中 backendUrl 的值是多少?
-
为什么要写文件?
-
@MindSwipe 使用
var byteArray = File.ReadAllBytes(file);给了我完全相同的错误。我不能直接在Client.PostAsync中使用它,因为它抱怨内容格式。 @John 好的,谢谢,所以据我了解,这不是 cors 问题。
标签: javascript c# http http-headers cors