【问题标题】:The 'Content-Length' header must be modified using the appropriate property or method. Parameter name: name必须使用适当的属性或方法修改“Content-Length”标头。参数名称:名称
【发布时间】:2017-02-28 12:34:25
【问题描述】:

我尝试使用 WebClient 将数据发送到 webapi。 运行我的代码会给出标题中显示的异常。 有人可以帮我吗?

这是我的代码的一部分,带有标题定义

using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                wc.Headers[HttpRequestHeader.Authorization] = headerString;

                data = Encoding.UTF8.GetBytes(jsonData);
                string contentLength = data.Length.ToString();

                wc.Headers[HttpRequestHeader.ContentLength] = contentLength;
                wc.Headers[HttpRequestHeader.Accept] = "application/json";

                wrCache = new CredentialCache();
                wrCache.Add(new Uri(URI), "Basic", new NetworkCredential("user1", "f_k@1F7"));

                wc.Credentials = wrCache;


                byte[] htmlResult = wc.UploadData(URI, "POST", data);

【问题讨论】:

    标签: webclient


    【解决方案1】:

    您可以使用HttpWebRequest。例如:

    private static HttpStatusCode UploadSharepointFile(string fileName)
    {
            // Read file from path
            byte[] buffer = File.ReadAllBytes(fileName);
    
            HttpWebRequest http =
                WebRequest.CreateHttp($"https://google.com");
    
            http.Method = "POST";
    
            http.Credentials = (ICredentials) Program.cred;
    
            http.Headers.Add("Accept", "application/json");
            http.ContentLength = buffer.Length;
            http.GetRequestStream().Write(buffer, 0, buffer.Length);
    
            HttpWebResponse response = (HttpWebResponse) http.GetResponse();
            return response.StatusCode;
    }
    

    【讨论】:

    • 是的,上面的错误来自于尝试添加名为“content-length”的标题。而是使用 HttpWebRequest 属性“ContentLength”。
    【解决方案2】:

    如下代码所示,通过将内容长度属性“ContentLength”添加到 WebClient 标头来设置它。

    using (WebClient wc = new WebClient())
    {
        wc.Headers[HttpRequestHeader.ContentType] = "application/json";
        -
        -
        -
        //wc.Headers[HttpRequestHeader.ContentLength] = contentLength;
        wc.Headers.Add("Content-Length", 0); //if there is no request body to be sent
              or 
        wc.Headers.Add("Content-Length", data.length.ToString());
        -
        -
        -
        -
        byte[] htmlResult = wc.UploadData(URI, "POST", data);
    

    【讨论】:

    • WebClient没有这个属性,ContentLength是HTTPRequest的属性。
    • ContentLength 作为标头添加到 WebClient,请检查上面的代码。它的 wc.Headers.Add("Content-Length", data.length.ToString());而不是 wc.Content-Length
    • 更新了上面的描述。
    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    相关资源
    最近更新 更多