如何使用 HttpClient 发出 OPTIONS 请求
Posted
技术标签:
【中文标题】如何使用 HttpClient 发出 OPTIONS 请求【英文标题】:how to make an OPTIONS request with HttpClient 【发布时间】:2019-04-19 20:04:41 【问题描述】:如何使用 System.Net.Http.HttpClient 发送 OPTIONS 请求
HttpClient 的公开方法
删除异步 GetAsync 后异步 PutAsync 其他人也很少.....我期待一个 OptionsAsync
switch (httpMethod)
case HTTP_METHODS.DELETE:
httpResponseMessage = httpClient.DeleteAsync(uri).Result;
break;
case HTTP_METHODS.GET:
httpResponseMessage = httpClient.GetAsync(uri).Result;
break;
case HTTP_METHODS.POST:
httpResponseMessage = httpClient.PostAsync(uri, httpContent).Result;
break;
case HTTP_METHODS.PUT:
httpResponseMessage = httpClient.PutAsync(uri, httpContent).Result;
break;
case HTTP_METHODS.OPTION:
//not sure what method to call on httpclient here to make Options request
httpResponseMessage = httpClient.PutAsync(uri, httpContent).Result;
if (httpResponseMessage.Headers.Contains("X-CSRF-TOKEN"))
IEnumerable < string > headerValues = httpResponseMessage.Headers.GetValues("X-CSRF-TOKEN");
csrfToken = headerValues.FirstOrDefault();
break;
【问题讨论】:
你看过这个吗:***.com/questions/6660019/… 【参考方案1】:这种方法没有包装器(例如OPTIONS
和HEAD
),但您可以像这些包装器一样使用SendAsync
:
var request = new HttpRequestMessage(HttpMethod.Options, "url");
var result = await _httpClient.SendAsync(request);
【讨论】:
【参考方案2】:为了获得预期的响应,您必须确保在请求中设置“Origin”标头,如下所示:
using var client = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Options, "url");
message.Headers.Add("Origin", "http://example.com");
var response = await client.SendAsync(message);
【讨论】:
以上是关于如何使用 HttpClient 发出 OPTIONS 请求的主要内容,如果未能解决你的问题,请参考以下文章