.Net Core代理

时间:2017-07-20 15:48:33

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

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

这是我的ProxyController:

[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而不是object,它们总是为null。我想保持它的通用性,所以我不能像通常那样定义匹配特定体的对象。

我使用的是AspNetCore 1.1.2。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

确实应该使用它。

问题是ActiveCell.Formula = "=COUNTIF(C35:AG35, "">=4000"")" 不是正确的请求有效负载。我用new StringContent(body.ToString())替换它,它现在工作正常!

相关问题