【问题标题】:How to use PostAsJsonAsync as a generic function?如何使用 PostAsJsonAsync 作为通用函数?
【发布时间】:2020-02-10 19:51:56
【问题描述】:

我需要编写一个可用于任何类对象的辅助方法。简而言之,我需要使 PostAsJsonAsync 方法通用。现在是这样的:

public HttpResponseMessage POSTRequest(StudentViewModel student)
{
    using (var client = new System.Net.Http.HttpClient())
    {
        client.BaseAddress = new Uri(_BaseAddress);

        var postTask = client.PostAsJsonAsync<StudentViewModel>("student", student);
        postTask.Wait();

        var result = postTask.Result;

        return result;
    }
}

如果我像上面那样使用它,我需要为其他视图模型对象的每个请求编写它。我怎样才能重写它,使它成为所有 POST 请求的通用方法?

【问题讨论】:

标签: c# httprequest


【解决方案1】:

你可以这样试试。 首选使用async await

async Task<HttpResponseMessage> 
                  PostGenericMessage<T>(string apiEndpoint, T typeofYourClass) where T : class
{

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("uri");

        var postTask = client.PostAsJsonAsync(apiEndpoint, typeofYourClass);
        return await postTask;
    }

}

【讨论】:

    【解决方案2】:

    你应该可以这样做:

    public HttpResponseMessage PostRequest<T>(T value)
    {
        using (var client = new System.Net.Http.HttpClient())
        {
            client.BaseAddress = new Uri(_BaseAddress);
    
            var postTask = client.PostAsJsonAsync<T>("student", value);
            var result = postTask.Result; // Task.Result waits for the result: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.8
            return result;
        }
    }
    

    或像这样异步:

    public async HttpResponseMessage PostRequestAsync<T>(T value)
    {
        using (var client = new System.Net.Http.HttpClient())
        {
            client.BaseAddress = new Uri(_BaseAddress);
            return await client.PostAsJsonAsync<T>("student", value);
        }
    }
    

    我在 PostAsJsonAsync 上没有看到任何类型约束,所以没有 where T : class 应该没问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2016-05-18
      • 1970-01-01
      • 2023-03-08
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多