Https上传MultipartForm返回401未经授权

时间:2015-05-29 15:07:14

标签: c# forms file-upload https http-status-code-401

我正在尝试将coverity扫描结果上传到覆盖率。

这是我的代码:

public static void Main( String[] args )
{
    var client = new HttpClient
    {
        Timeout = TimeSpan.FromMinutes( 20 )
    };
    var form = new MultipartFormDataContent
    {
        { new StringContent( "my tooken" ), "token" },
        { new StringContent( "my email" ), "email" },
        { new StringContent( "1.1.1.1" ), "version" },
        { new StringContent( "Test..." ), "description" }
    };

    var fs = new FileStream( @"cov-int.zip", FileMode.Open, FileAccess.Read );
    form.Add(new StreamContent(fs), "file", "cov-int.zip");

    var task = client.PostAsync("https://scan.coverity.com/builds?project=Name/Porject", form);
    try
    {
        task.Wait();
    }
    catch ( AggregateException ex )
    {
        throw ex.InnerException;
    }
    var result = task.Result;
    fs.Close();
}

帖子总是以失败状态结束(401未经授权):

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  x-xss-protection: 1; mode=block
  x-request-id: 70dfc119-7d78-47fe-86a7-8505d73225e4
  x-runtime: 1.675468
  x-frame-options: SAMEORIGIN
  x-content-type-options: nosniff
  Connection: close
  Status: 401 Unauthorized
  Transfer-Encoding: chunked
  Cache-Control: no-cache
  Date: Fri, 29 May 2015 13:01:06 GMT
  Server: Apache
  X-Powered-By: Phusion Passenger 5.0.8
  Content-Type: text/html; charset=utf-8
}}

我尝试使用curl:

将相同的数据从同一台机器上传到同一台服务器
curl --form token="token" --form email="email" --form file="cov-int.zip" --form version="1.1.1.1" --form description="a message" --insecure https://scan.coverity.com/builds?project=Name/Project

使用curl上传数据。

我的C#代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

Coverity结束时可能会发生一些变化,因为这是两周前的工作。基于这里的另一个问题How to upload files to Asp.Net MVC 4.0 action running in IIS Express with HttpClient class included in .Net 4.0我发现了我认为的解决方案。

您需要在表单数据名称中添加额外的引号。

var form = new MultipartFormDataContent
{
    { new StringContent( "my tooken" ), "\"token\"" },
    { new StringContent( "my email" ), "\"email\"" },
    { new StringContent( "1.1.1.1" ), "\"version\"" },
    { new StringContent( "Test..." ), "\"description\"" }
};

form.Add(new StreamContent(fs), "\"file\"", "cov-int.zip");

不能100%肯定这是有效的,因为我用尽了今天的所有尝试,并且必须等到明天才能看到成功的回应。但我现在收到"The build submission quota for this project has been reached."消息而不是“拒绝访问”消息。