如何将 PostAsJsonAsync 用作通用函数?
How to use PostAsJsonAsync as a generic function?
我需要编写一个可重复用于任何 class 对象的辅助方法。简而言之,我需要使 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 请求的通用方法?
你可以这样试试。
首选使用 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;
}
}
你应该可以这样做:
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
应该没问题
我需要编写一个可重复用于任何 class 对象的辅助方法。简而言之,我需要使 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 请求的通用方法?
你可以这样试试。
首选使用 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;
}
}
你应该可以这样做:
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