简体   繁体   English

如何使用“no-cors”将 JavaScript HTTP post 请求代码更改为 C#?

[英]How can I change JavaScript HTTP post request code to C#, using 'no-cors'?

I am trying to do the same thing that is done in the JavaScript code but in C#.我正在尝试执行在 JavaScript 代码中但在 C# 中完成的相同操作。 The end result would be that I want to automate this task from a C# code where I will create these files manually.最终结果是我想通过 C# 代码自动执行此任务,我将在其中手动创建这些文件。 This code is being used for the web page in order to achieve its goal:此代码用于网页以实现其目标:

The First function is placing the file in a buffer a place.第一个功能是将文件放置在缓冲区中的一个地方。

        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);
        

The Second function is calling this file to be run on the site.第二个函数调用这个文件在站点上运行。

          fetch(`${props.configuration.backendUrl}/www.RunFile?name=${e.currentTarget.id}`); 
        

The way how I am mimicking this is by:我模仿的方式是:

        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);
       
    }

and the second part is:第二部分是:

    public async static Task RunFile(string fileName)
    {
        var response = await Client.PostAsync(
            $"https://localhost/www.RunFile?name="+$"{fileName}", null);           
    }

Once I call this function I get the response 405 , though this possible looks like I need to set the 'no-cors' in C# as per the JavaScript, though I am not sure how to do this.一旦我调用这个函数,我就会得到响应405 ,尽管这可能看起来像我需要根据 JavaScript 在 C# 中设置“no-cors”,但我不知道如何做到这一点。 But there could be other issues with this, which I am not seeing.但是这可能还有其他问题,我没有看到。

{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
}}

As John has outlined in the comments, no-cors is not a server side thing that you need to replicate.正如约翰在评论中概述的那样,no-cors 不是您需要复制的服务器端事物。 CORS is a browser feature whereby if JavaScript makes a request to download content from somewhere other than where the JavaScript file itself came from, then the browser (as a courtesy) checks with the destination server "for your url x, what places may a JavaScript have been downloaded from and be permitted to access x?" CORS 是一种浏览器功能,如果 JavaScript 请求从 JavaScript 文件本身的来源以外的地方下载内容,那么浏览器(作为礼貌)会检查目标服务器“对于您的 url x,JavaScript 可能在哪些地方已经从 x 下载并被允许访问 x?” - this gives the server the opportunity to respond with "only JavaScript from these places a,b,c may request my file x" and the browser then makes a judgement as to whether the JavaScript currently running, may access x - 这让服务器有机会响应“只有来自 a,b,c 的 JavaScript 可以请求我的文件 x”,然后浏览器判断当前运行的 JavaScript 是否可以访问 x

You can turn this off if you can tolerate the restrictions that come with doing so, and that's what no-cors does;如果您可以容忍这样做带来的限制,您可以关闭它,这就是 no-cors 所做的; it changes the browser behavior它改变了浏览器的行为

As such, you can hopefully see that no-cors is an instruction to the browser and with your c# you're effectively taking the browser out of the equation so it's unlikely that mimicking it will change the server behavior.因此,您希望看到 no-cors 是对浏览器的指令,并且使用您的 c#,您可以有效地将浏览器排除在外,因此模仿它不太可能改变服务器行为。 It's theoretically possible;理论上是可能的; your server might be coded to refuse access to a url that it hasn't seen an OPTIONS request for recently(browsers in CORS mode send an options first), but it's actually more likely that the root cause is something simpler like you're Posting to an action that is coded to expect a Get您的服务器可能被编码为拒绝访问它最近没有看到 OPTIONS 请求的 url(CORS 模式下的浏览器首先发送一个选项),但实际上更可能是根本原因更简单,例如您正在发布到一个被编码为期待 Get 的动作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 no-cors 的 fetch 请求中更改 Header? - How to change Header in fetch request at no-cors? 使用模式:无要求时,浏览器未添加我在前端代码中设置的请求标头 - When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code 我可以将这个向 Azure 计算机服务发送的 C# http POST 请求转换为 JavaScript 吗? - Can I transform this C# http POST request to Azure Computer Service to JavaScript? 如何让我的 C# API 响应来自我的 React 应用程序的 POST 请求? (CORS问题) - How can I get my C# API to respond to a POST request from my React app? (CORS issue) 如何从C#服务器中的POST(或其他HTTP)请求访问参数? - How can I access parameters from a POST (or other HTTP) request in a C# server? 如何修复将请求的模式设置为“no-cors”? - How to fixed set the request's mode to 'no-cors'? 如果发生错误,如何更改http发布请求的网址 - How can i change the url of a http post request if there is an error 我们如何使用JavaScript发送HTTP POST请求? - How can we send a HTTP POST request by using JavaScript? 如何在 fetch() 中使用 no-cors - How use no-cors with fetch() 如何在模式为“ no-cors”的情况下使用获取API获取数据? - How to get data using fetch API with mode 'no-cors'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM