将对象数据从控制台应用程序发布到Web API

时间:2018-08-28 21:44:03

标签: c# asp.net-web-api asp.net-core console-application

我正在.Net Core中创建一个控制台应用程序,该应用程序从Web API获取数据,更新该数据,并执行Put操作以更新Web API数据。我遇到一个问题,当我将数据发送到HttpContent时,我在HttpRequestBuilder上丢失了数据,并且Web API没有得到更新,但返回了200。有什么想法我可能做错了吗?

控制器:

public static async Task<HttpResponseMessage> UpdateTransaction(Transaction transaction)
{
    var requestUri = $"{baseUri}transactions/{transaction.ID}";
    return await HttpRequestFactory.Put(requestUri, transaction);
}

JsonContent:

public JsonContent(object value, string mediaType)
        :base(JsonConvert.SerializeObject(value), Encoding.UTF8, mediaType)
{
}

HttpRequestFactory:

public static async Task<HttpResponseMessage> Put(string requestUri, object value)
{
    var builder = new HttpRequestBuilder()
        .AddMethod(HttpMethod.Put)
        .AddRequestUri(requestUri)
        .AddContent(new JsonContent(value, "application/json"));

    return await builder.SendAsync();
}

HttpRequestBuilder:

 public HttpRequestBuilder AddContent(HttpContent content)
{
    this.content = content;
    return this;
}

public async Task<HttpResponseMessage> SendAsync()
{
    // Check required arguments
    EnsureArguments();

    // Setup request
    var request = new HttpRequestMessage
    {
        Method = this.method,
        RequestUri = new Uri(this.requestUri)
    };

    if (this.content != null)
        request.Content = this.content;

    request.Headers.Accept.Clear();
    if (!string.IsNullOrEmpty(this.acceptHeader))
        request.Headers.Accept.Add(
            new MediaTypeWithQualityHeaderValue(this.acceptHeader));

    // Setup client
    var client = new HttpClient();
    client.Timeout = this.timeout;

    var response = await client.SendAsync(request);

    return response;
}

1 个答案:

答案 0 :(得分:0)

我不认为JsonContent类在做正确的事情。我们缺少完整的类定义,所以我只能猜测:

当您使用Put方法调用它时,它会将一个对象返回到.AddContent,但这可能不会被序列化为内容字符串。

更改您的Put方法以直接调用JsonConvert方法。

HttpRequestFactory:

public static async Task<HttpResponseMessage> Put(string requestUri, object value)
{
    var builder = new HttpRequestBuilder()
        .AddMethod(HttpMethod.Put)
        .AddRequestUri(requestUri)
        .AddContent(JsonConvert.SerializeObject(value, Encoding.UTF8, "application/json"));

    return await builder.SendAsync();
}

如果您确实想使用JsonContent类,那么使用静态方法而不是类层次结构来进行转换可能会更好?