Webclient ';内容长度';必须使用适当的属性或方法修改标题。参数名称:name

Webclient ';内容长度';必须使用适当的属性或方法修改标题。参数名称:name,webclient,Webclient,我尝试使用WebClient将数据发送到webapi。 运行我的代码会出现标题中显示的异常。 有人能帮我吗 这里是我的部分代码和标题定义 using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/json"; wc.Headers[HttpRequestHeader.Aut

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

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

设置WebClient对象的内容长度属性“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);