C# 使用Windows.Web.Http.HttpClient类修补异步请求
我需要使用C# 使用Windows.Web.Http.HttpClient类修补异步请求,c#,http,patch,dotnet-httpclient,C#,Http,Patch,Dotnet Httpclient,我需要使用Windows.Web.Http.HttpClient类执行PATCH请求,并且没有关于如何执行的正式文档。我该怎么做呢?我找到了如何使用以前的System.Net.Http.HttpClient类执行一个“自定义”补丁请求,然后在Windows.Web.Http.HttpClient类中进行修改,直到我使它可以工作,如下所示: public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri
Windows.Web.Http.HttpClient
类执行PATCH
请求,并且没有关于如何执行的正式文档。我该怎么做呢?我找到了如何使用以前的System.Net.Http.HttpClient
类执行一个“自定义”补丁
请求,然后在Windows.Web.Http.HttpClient
类中进行修改,直到我使它可以工作,如下所示:
public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri) {
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
// In case you want to set a timeout
//CancellationToken cancellationToken = new CancellationTokenSource(60).Token;
try {
response = await client.SendRequestAsync(request);
// If you want to use the timeout you set
//response = await client.SendRequestAsync(request).AsTask(cancellationToken);
} catch(TaskCanceledException e) {
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
公共异步任务PatchAsync(HttpClient客户端,Uri请求Uri,IHttpContent iContent){
var方法=新的HttpMethod(“补丁”);
var request=newhttprequestmessage(方法,requestUri){
Content=i内容
};
HttpResponseMessage response=新的HttpResponseMessage();
//如果你想设置一个超时
//CancellationToken CancellationToken=新的CancellationTokenSource(60).Token;
试一试{
response=wait client.SendRequestAsync(请求);
//如果要使用设置的超时值
//response=wait client.SendRequestAsync(request).AsTask(cancellationToken);
}捕获(TaskCanceledException e){
Debug.WriteLine(“错误:+e.ToString());
}
返回响应;
}
更新:请参见下文,以获得更好的解决方案,该解决方案也可以实现同样的效果
您可以编写与扩展方法完全相同的方法,因此可以直接在HttpClient对象上调用它:
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent iContent)
{
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri)
{
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.SendAsync(request);
}
catch (TaskCanceledException e)
{
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
}
我想扩展@alexander pacha的答案,并建议在公共库的某个地方添加以下扩展类。这是否是项目/客户机/框架/的公共库。。。这是你必须自己做的事情
public static class HttpClientExtensions
{
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content)
{
return client.PatchAsync(CreateUri(requestUri), content);
}
/// <summary>
/// Send a PATCH request to the specified Uri as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content)
{
return client.PatchAsync(requestUri, content, CancellationToken.None);
}
/// <summary>
/// Send a PATCH request with a cancellation token as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return client.PatchAsync(CreateUri(requestUri), content, cancellationToken);
}
/// <summary>
/// Send a PATCH request with a cancellation token as an asynchronous operation.
/// </summary>
///
/// <returns>
/// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation.
/// </returns>
/// <param name="client">The instantiated Http Client <see cref="HttpClient"/></param>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="client"/> was null.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception>
public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return client.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)
{
Content = content
}, cancellationToken);
}
private static Uri CreateUri(string uri)
{
return string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute);
}
}
公共静态类HttpClientExtensions
{
///
///将修补程序请求作为异步操作发送到指定的Uri。
///
///
///
///返回。表示异步操作的任务对象。
///
///实例化的Http客户端
///请求发送到的Uri。
///发送到服务器的HTTP请求内容。
///结果为空。
///结果为空。
公共静态任务PatchAsync(此HttpClient客户端、字符串请求URI、HttpContent)
{
返回client.PatchAsync(CreateUri(requestUri),content);
}
///
///将修补程序请求作为异步操作发送到指定的Uri。
///
///
///
///返回。表示异步操作的任务对象。
///
///实例化的Http客户端
///请求发送到的Uri。
///发送到服务器的HTTP请求内容。
///结果为空。
///结果为空。
公共静态任务PatchAsync(此HttpClient客户端、Uri请求Uri、HttpContent)
{
返回client.PatchAsync(requestUri、content、CancellationToken.None);
}
///
///作为异步操作发送带有取消令牌的修补程序请求。
///
///
///
///返回。表示异步操作的任务对象。
///
///实例化的Http客户端
///请求发送到的Uri。
///发送到服务器的HTTP请求内容。
///可由其他对象或线程用于接收取消通知的取消令牌。
///结果为空。
///结果为空。
公共静态任务PatchAsync(此HttpClient客户端、字符串请求URI、HttpContent内容、CancellationToken CancellationToken)
{
返回client.PatchAsync(CreateUri(requestUri)、content、cancellationToken);
}
///
///作为异步操作发送带有取消令牌的修补程序请求。
///
///
///
///返回。表示异步操作的任务对象。
///
///实例化的Http客户端
///请求发送到的Uri。
///发送到服务器的HTTP请求内容。
///可由其他对象或线程用于接收取消通知的取消令牌。
///结果为空。
///结果为空。
公共静态任务PatchAsync(此HttpClient客户端、Uri请求Uri、HttpContent内容、CancellationToken CancellationToken)
{
返回client.sendsync(新的HttpRequestMessage(新的HttpMethod(“补丁”),requestUri)
{
内容=内容
},取消令牌);
}
私有静态Uri CreateUri(字符串Uri)
{
返回字符串.IsNullOrEmpty(uri)?null:新uri(uri,UriKind.RelativeOrAbsolute);
}
}
这样,您就不必在某个静态扩展类中等待和延迟执行,而是可以像处理
PostAsync
或PutAsync
调用一样处理它。您还可以使用相同的重载,让HttpClient
处理它设计用来处理的所有内容。要让它工作,您需要像这样传递内容:
HttpContent httpContent = new StringContent("Your JSON-String", Encoding.UTF8, "application/json-patch+json");
步骤1:创建一个静态类(我已创建为扩展)
公共静态类扩展
{
公共静态任务patcasjsonasync(此HttpClient
客户端,字符串请求URI,T值)
{
var content=newobjectcontent(值,new-JsonMediaTypeFormatter());
var request=newhttprequestmessage(newhttpmethod(“补丁”),requestUri)
{Content=Content};
返回client.sendaync(请求);
}
}
步骤2:在api请求中调用此方法
private static HttpClient client = new HttpClient();
var response = Extention.PatchAsJsonAsync<UserUpdateAPIModel>(client, "https://api.go1.com/v2/users/5886043", data);
private static HttpClient=new HttpClient();
var response=Extention.PatchAsJsonAsync(客户端,“https://api.go1.com/v2/users/5886043“,数据);
问题解决了,这里若它是公共url,那个么你们可以用你们的pra来做
public static class Extention
{
public static Task<HttpResponseMessage> PatchAsJsonAsync<T>(this HttpClient
client, string requestUri, T value)
{
var content = new ObjectContent<T>(value, new JsonMediaTypeFormatter());
var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)
{ Content = content };
return client.SendAsync(request);
}
}
private static HttpClient client = new HttpClient();
var response = Extention.PatchAsJsonAsync<UserUpdateAPIModel>(client, "https://api.go1.com/v2/users/5886043", data);