System.Net.WebException-内部服务器错误500

时间:2019-02-18 12:24:18

标签: c# console

当我使用HttpWebRequest使用C#控制台应用程序进行Web API时发生异常

  

远程服务器返回错误:(500)内部服务器错误。

这是我的代码:

string postURL = "";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postURL);

webRequest.Method = "POST";

webRequest.Headers.Add("token", "ee22c61a55bd0629c8c8a63a8c8b73ed");            

webRequest.KeepAlive = true;
webRequest.ContentType = "application/json";

webRequest.Headers.Add("ContentType","application/json");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
FileInfo finfo = new FileInfo(@"D:\audio\smallwave.zip");
webRequest.ContentLength = finfo.Length;
// webRequest.SendChunked = true;

using (FileStream fileStream = File.OpenRead(@"D:\audio\smallwave.zip"))
using (Stream requestStream = webRequest.GetRequestStream())
{
    while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
    {
        requestStream.Write(buffer, 0, byteCount);
    }
}

HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
// using (WebResponse response = webRequest.GetResponse())
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    String result = streamReader.ReadToEnd();
    Console.WriteLine(result);
}

显示错误

  

类型为'System.Net.WebException'的未处理异常发生在   System.dll   附加信息:远程服务器返回错误:(500)   内部服务器错误。

1 个答案:

答案 0 :(得分:-1)

using HTTPClient


string baseUrl = "https://vspark-demo.vocitec.com/transcribe/M2ComSys-Pilot/eng1CCStereo/";



            HttpClient client = new HttpClient();

            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("file");
            HttpContent DictionaryItems = new FormUrlEncodedContent(new[] {
       new KeyValuePair<string, string>("token", "ee22c61a55bd0629c8c8a63a8c8b73ed"),
   });
            form.Add(content, "files");
            // form.Add(DictionaryItems, "data");
            form.Add(new StringContent("ee22c61a55bd0629c8c8a63a8c8b73ed"), "token");
             var stream = new FileStream(@"D:\audio\variety.wav", FileMode.Open);
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "file",
                FileName = "variety.wav"
            };
            form.Add(content);

            HttpResponseMessage response = null;

            try
            {
                response = (client.PostAsync(baseUrl, form)).Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine(response);
            var k = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(k);
            Console.ReadLine();
        }