【问题标题】:Send File and data with C# error 403. No error with CURL发送带有 C# 错误 403 的文件和数据。CURL 没有错误
【发布时间】:2019-09-08 21:36:15
【问题描述】:

我正在尝试从我的 C# 程序通过 POST 请求将文件和一些数据上传到我的服务器,但我总是收到错误 403。

帖子参数是 "id" = 保存文件的文件夹 "pos" = 文件名

因此,如果用户上传文件“abc.text”且 POST 数据为 id="Mario" pos="first",则该文件将保存在 /users/Mario/first.txt 中

我尝试将参数 id 和 pos 更改为 GET,但总是出现错误 403

C# 响应

{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, 
Content: System.Net.Http.StreamContent, 
Headers:{  Vary: Accept-Encoding  X-Varnish: 818481486  Age: 0  
X-Cache: MISS  Transfer-Encoding: chunked  Connection: keep-alive  
Date: Thu, 18 Apr 2019 14:29:10 GMT  Content-Type: text/html; 
charset=iso-8859-1}}

我的代码:

<!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <form enctype="multipart/form-data" action="uploader2.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="input" name="id"></input><br />
    <input type="input" name="pos"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>
<!-- language: lang-php -->
<?PHP
  if(!empty($_FILES['uploaded_file']))
  {
    $path = "users/".$_POST['id']."/";

    if(!is_dir($path))  
        {  
        if(!mkdir ($path,0777,true))
            echo 'Error creating folder!';  
        }  

    $path = $path.$_POST['pos'].".txt";

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
      echo "Ok";
    } else{
        echo "Failed!";
    }
  }
?>

这是我的 C# 代码

using (var httpClient = new HttpClient())
{   
    MultipartFormDataContent multipartContent = new MultipartFormDataContent();
    var fp = File.ReadAllBytes("file.txt");

    multipartContent.Add(new StringContent("Mario"), "id");
    multipartContent.Add(new StringContent("first"), "pos");
    multipartContent.Add(new ByteArrayContent(fp, 0, fp.Length), "uploaded_file", "file.txt");
    HttpResponseMessage response = await httpClient.PostAsync("http://host.com/uploader2.php", multipartContent);

    response.EnsureSuccessStatusCode();
    httpClient.Dispose();
    string sd = response.Content.ReadAsStringAsync().Result;
    }
}

【问题讨论】:

    标签: c# php post upload http-status-code-403


    【解决方案1】:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    在你的 php 脚本中使用它:

    header("Access-Control-Allow-Origin: *"); // wildcard allows access to all domains
    

    Access-Control-Allow-Origin 是一个 CORS(跨域资源共享)标头。

    当站点 A 尝试从站点 B 获取内容时,站点 B 可以发送一个 Access-Control-Allow-Origin 响应标头,告诉浏览器该页面的内容可以从某些来源访问。 (来源是一个域,加上一个方案和端口号。)默认情况下,任何其他来源都无法访问站点 B 的页面。使用 Access-Control-Allow-Origin 标头为特定请求来源的跨域访问打开了大门。

    【讨论】:

    • 感谢您的回答。问题仍然存在。如果有帮助,我已经用 C# 响应更新了主帖
    猜你喜欢
    • 2017-12-15
    • 2017-01-18
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多