简体   繁体   English

HTTP 使用 C# HttpClient 时收到 500 响应

[英]HTTP 500 response is received when using C# HttpClient

I have developed a C# application that calls a REST service existing in some PC in the.network.我开发了一个 C# 应用程序,它调用 .network 中某些 PC 中存在的 REST 服务。

This is the code to make a request:这是发出请求的代码:

    public async Task<bool> OpenDoorAsync(string name, int delay)
    {
        var data = await CallApiAsync("api/door/remoteOpenByName", new Dictionary<string, string> { { "doorName", name }, { "interval", delay.ToString() } });
        return data.IsSuccess;
    }

    private async Task<ResponseData> CallApiAsync(string endPoint, Dictionary<string, string> parameters)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");

                var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                string fullUri = "http://192.168.0.122:8088/api/door/remoteOpenByName?doorName=10.185.85.237-1&interval=5&access_token=1234";
                HttpResponseMessage response = await client.PostAsync(fullUri, content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<ResponseData>(responseBody);
            }
        }
        catch (Exception ex)
        {
            OnError("Existió un error al realizar la llamada.", ex);
            return new ResponseData()
            {
                message = "failed"
            };
        }
    }

Entry point is OpenDoorAsync , called this way, from a Winform form:入口点是OpenDoorAsync ,从 Winform 表单中这样调用:

await _device.OpenDoorAsync(TxtNombrePuerta.Text.Trim(), IntInterval.Value);

Well, after the execution of PostAsync method, a HTTP 500 error is returned:那么, PostAsync方法执行后,返回了HTTP 500错误:

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Connection: close
  Date: Thu, 28 Jan 2021 21:06:35 GMT
  Set-Cookie: JSESSIONID=4062B932CDB44B4CA3FCCC275937AC15; Path=/; HttpOnly
  Server: Apache-Coyote/1.1
  Content-Length: 2580
  Content-Language: en
  Content-Type: text/html; charset=utf-8
}}

However, if I make the same request using Google Chrome RESTED extension, it works perfectly:但是,如果我使用 Google Chrome RESTED 扩展程序发出相同的请求,它会完美运行:

休息电话

Just in case, I analyzed Google Chrome developer tools after the RESTED call and I have not found anything weird.为了以防万一,我在 RESTED 调用后分析了 Google Chrome 开发人员工具,但没有发现任何奇怪的东西。 I thought maybe I missed to send something else in the headers.我想也许我错过了在标题中发送其他内容。

开发者工具

Does anybody know what is happening with the call from the C# application?有人知道来自 C# 应用程序的调用发生了什么吗? Clearly, I am not doing something that RESTED is.显然,我没有做 RESTED 做的事情。

I don't really know why it does not work when using HttpClient class, however, I solved the problem installling an using RestSharp NuGet package.我真的不知道为什么它在使用HttpClient class 时不起作用,但是,我解决了安装使用 RestSharp NuGet package 的问题。

Finally, the code was reduced to this:最后,代码被简化为:

private ResponseData CallApi(string endPoint, Dictionary<string, string> parameters)
{
    try
    {
        string fullUri = $"http://{GetServerIp()}:{((MainWindow)MainWindow).ServerPort}/{endPoint}?{GetQueryParameters(parameters)}";
        var client = new RestClient(fullUri);
        var request = new RestRequest(Method.POST);
        var response = client.Execute(request);
        return JsonConvert.DeserializeObject<ResponseData>(response.Content);
    }
    catch (Exception ex)
    {
        OnError("Existió un error al realizar la llamada.", ex);
        return new ResponseData()
        {
            message = "failed"
        };
    }
}

Your working example is passing cookies, which may be required for the API you're calling.您的工作示例正在传递 cookies,这可能是您呼叫的 API 所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM