【问题标题】:.Net Core Making a Proxy.Net Core 制作代理
【发布时间】:2017-07-20 15:48:32
【问题描述】:

我正在尝试开发一个简单的代理,假设在我的第一个应用程序和我的第二个应用程序之间转发 api 请求。对于 Get 请求,它工作得很好,但我现在正试图用实际的身体转发一个请求,但它没有成功。我考虑过为此使用 middelware,但我不认为使用 middelware 可以解决这个特定问题。

这是我的代理控制器:

[HttpGet("/api/corporations/{*url}")]
public async Task<string> GetCorporations(string url)
{
    var result = await _httpClient.GetAsync("SomeCoolUrl");
    Response.ContentType = "application/json";
    return await result.Content.ReadAsStringAsync();
}

[HttpPatch("/api/corporations/{*url}")]
public async Task<string> PatchCorporations(string url, [FromBody]object body)
{
    var result = await HttpClientExtension.PatchAsync(_httpClient, "SomeCoolUrl", new StringContent(body.ToString()));
    Response.ContentType = "application/json";
    return await result.Content.ReadAsStringAsync();
}

我像这样实现了 PatchAsync(在 HttpClientExtension 中):

public static async Task<HttpResponseMessage> PatchAsync(HttpClient httpClient, string url, StringContent content)
{
    return await httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), url) { Content = content });
}

问题是我在发送补丁请求时得到了不受支持的媒体类型,因为 object.tostring() 不是有效的 json。但我无法弄清楚使用什么类型的对象来正确保留补丁请求正文。如果我尝试使用 String 或 StringContent 而不是对象,它们始终为空。我想保持其通用性,因此我无法像通常那样定义与特定主体匹配的对象。

我正在使用 AspNetCore 1.1.2。

【问题讨论】:

    标签: .net asp.net-core .net-core asp.net-core-webapi


    【解决方案1】:

    “不支持的媒体类型”将是您的应用程序无法根据请求的内容类型将其 PatchCorporations 绑定到 it 的结果。使用 string body 而不是 object body 以便 ASP.NET 可以将 HTTP 请求与其匹配。通常,content negotiation 将使用“application/json”或“application/xml”的内容类型(例如)通过parameter binding 将 HTTP 请求自动序列化/反序列化为正确的控制器方法。

    【讨论】:

    • 调试器可以正常运行。当 body 是对象体时,它不为空。但是当它是一个字符串时它是空的。结果中出现了不支持的媒体类型。
    • 据此可能不应该有 json 内容类型? tools.ietf.org/html/rfc5789
    【解决方案2】:

    确实是应该使用的对象。

    问题是new StringContent(body.ToString()) 不是正确的请求负载。我将其替换为new StringContent(content: JsonConvert.SerializeObject(body), encoding: Encoding.UTF8, mediaType: "application/json");,现在可以正常使用了!

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多