【问题标题】:HttpPatchAsync working on windows but not LinuxHttpPatchAsync 适用于 Windows 但不适用于 Linux
【发布时间】:2021-09-29 09:30:06
【问题描述】:

我在 Linux 容器中运行的 .Net Core API 中有一个端点

[HttpPatch] // inside controller called Customer
public async Task<IActionResult> PatchAsync([FromBody] TestObject entity)
{
    return Ok(await _service.PatchAsync(entity));
}

波科

public class TestObject 
{
    [JsonProperty(PropertyName = "Code")]
    public string Code { get; set; }
    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }
}
    

在我的 Blazor 应用中,我有以下代码来更新实体

public async Task<bool> UpdateEntity(TestObject entity)
{
    var content = new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json");
    using (var httpClient = new HttpClient())
    {
        using (var response = await httpClient.PatchAsync(@"http://someserverpath:5000/api/v1/Customer", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<bool>(apiResponse);
        }
    }
}

当我在 Windows 10 上本地运行代码时遇到的问题,它可以工作。当我在 Linux docker 容器中运行此代码时,出现以下异常

错误:Newtonsoft.Json.JsonReaderException:意外字符 解析值时遇到:M. Path '', line 1, position 1.

【问题讨论】:

  • Linux 上运行的是什么? API? API 返回什么?我猜它会返回一条错误消息,这就是为什么您应该在使用 HttpClient 时检查 HTTP 响应代码。
  • API 总是在 linux 容器中运行。该应用程序是从 Windows 10 上的 Visual Studio 运行的,并且可以正常工作,当我在 linux 容器中本地运行该应用程序时,我得到了异常
  • api 没有返回响应代码我在 blazor.server.js:21 内收到一个致命错误 (Newtonsoft.Json.JsonReaderException) 所以我猜测它在 api 被命中之前发生了跨度>
  • 唯一的区别是 linux vs windows
  • 我在 Mac 上使用带有 Blazor Wasm 的 PATCh 并且没有问题。我也不使用 JSON.NET,因为 HTTP Patch 与 JSON 序列化程序无关。您自己的代码只是对内容进行序列化,System.Text.Json 可以很好地处理这些内容。异常抱怨 json 字符串。这个错误在哪里抛出?在客户端?服务器? full 异常文本是什么?全文是什么?

标签: .net linux docker asp.net-core .net-core


【解决方案1】:

试试这样的:

public async Task<bool> UpdateEntity(TestObject entity)
{
    var content = new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json");
    using var httpClient = new HttpClient();
    using var response = await httpClient.PatchAsync(@"http://someserverpath:5000/api/v1/Customer", content);
        
    string apiResponse = await response.Content.ReadAsStringAsync();
    if (response.IsSuccessStatusCode) {
        return JsonConvert.DeserializeObject<bool>(apiResponse);
    } else {
        throw new Exception("Something went wrong when.... See inner excpetion.", new Exception(apiResponse));
    }
}

您很可能收到了不成功的响应,需要返回 API 抛出的异常。以您通常在解决方案中的方式处理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2016-03-01
    • 2021-05-02
    • 2017-06-14
    • 2011-06-15
    • 2021-10-27
    相关资源
    最近更新 更多