必须使用适当的属性或方法修改“Content-Length”标头。参数名称:名称

时间:2017-02-28 12:34:26

标签: webclient

我尝试使用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);

2 个答案:

答案 0 :(得分:0)

您可以使用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;
}

答案 1 :(得分:0)

设置HttpWebRequest对象的内容长度属性“ ContentLength”,而不是将其添加到标头中。

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