在WebAPI的HttpResponseMessage/HttpRequestMessage类型中直观地查看将实际发送或接收的Http Headers的原始列表是非常有益的.我的意思是只是一个普通的旧字符串,每个标题都在一个新行上,正是生成或接收的内容.
但不幸的是,看起来这些类型中的任何一种都不允许您只看到实际生成的内容.相反,到处都有物业.原始HttpResponseMessage/HttpRequestMessage中的一些类型本身,一些在response/request.Content.Headers中(两个不重复,后者是那些尚未作为属性覆盖的,通常用于自定义标题),...也许Cookie某处获得了自己的标题藏匿处.并且在视觉上看到那些Header集合列表也很痛苦,也就是说你最终会为每个这样的集合添加一堆迭代代码......更多的混乱.
但是在发送/接收的实际响应/请求中,没有这样的划分,并且很容易看到所有Http头.所以我在某个地方错过了吗?实际上是否有一个简单直观的属性,只是返回原始标题字符串?当然响应已经收到了标题并且只是解析了它们...是隐藏在某处的原始字符串吗?
(顺便说一下,我知道Fiddler ......这完全不能令人满意.如果我不得不处理Http标题的低级别混乱,那么能够用我正在使用的编程类型来查看它们是很有意义的.生成和接收它们.但更糟糕的是,我仍然无法让localhost与Fiddler一起工作(在Win8上),这使得它在许多调试场景中的使用无效,我想要做的就是看到将生成的臭头. )
我的代码正在对需要基本身份验证的Web服务URL进行HTTP GET。
我用这个来实现HttpClient与HttpClientHandler具有Credentials定义的属性。
这一切都很好。.除了我的一个用例中,我将经过身份验证的GET发送到:
http://somedomain.com重定向到http://www.somedomain.com。
似乎HttpClientHandler在重定向过程中清除了身份验证标头。我该如何预防?我希望无论重定向如何都发送凭据。
这是我的代码:
// prepare the request
var request = new HttpRequestMessage(method, url);
using (var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) , PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
// send the request
var response = await client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
注意:这是一个相关的问题: 重定向时保持HTTP基本身份验证有效, 但是由于我使用不同的类进行请求,因此可能会有更好,更具体的解决方案
我有一个经过身份验证的HttpClient生成器类的实现,类似于:
public class X509Authentication : IClientAuthenticator
{
protected readonly X509Certificate2 Certificate;
public X509Authentication(X509Certificate2 certificate)
{
if (certificate == null) throw new ArgumentNullException("certificate");
Certificate = certificate;
}
public HttpClient GenerateClient()
{
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(Certificate);
var request = new HttpClient(clientHandler);
return request;
}
public void Dispose()
{
//nothing to do here.
}
}
Run Code Online (Sandbox Code Playgroud)
...如何测试该GenerateClient()方法是否已成功将客户端证书附加到HttpClient类中?
[TestMethod]
public void HttpClientCreationIncludesCertificate()
{
using (var auth = new X509Authentication(_certificate))
using (var client = auth.GenerateClient())
{
Assert...what? The …Run Code Online (Sandbox Code Playgroud) 这个问题之前已被问过几次,但我找不到明确的答案.甚至可以使用System.Net.Http.HttpClient获取响应cookie吗?
我试图在C#中使用HTTPClient对象将发布请求发送到API。这是CURL命令:
curl -X POST https://zzz.zzz.zzz/yyy -F Key=abcd -F media=@"audio.aac"
Run Code Online (Sandbox Code Playgroud)
我写了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Net.Http.Headers;
namespace Speech2Text
{
class Program
{
static void Main(string[] args)
{
curl().Wait();
}
static async Task curl()
{
var client = new HttpClient();
//Create List of KeyValuePairs
List<KeyValuePair<string, string>> bodyProperties = new List<KeyValuePair<string, string>>();
bodyProperties.Add(new KeyValuePair<string, string>("key", "abcd"));
bodyProperties.Add(new KeyValuePair<string, string>("media", "@audio.aac"));
var dataContent = new FormUrlEncodedContent(bodyProperties.ToArray());
HttpResponseMessage response = await client.PostAsync("https://zzz.zzz.zzz/yyy", dataContent);
HttpContent …Run Code Online (Sandbox Code Playgroud) 我有一个aspnetcore Web API,并使用以下代码为Windows Auth配置主机.
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls("http://TestServer:5000")
.UseStartup<Startup>()
.UseWebListener(options =>
{
options.Listener.AuthenticationManager.AuthenticationSchemes = Microsoft.Net.Http.Server.AuthenticationSchemes.NTLM;
//NOTE: Multiple auth assignments don't work in 1.0.0 - Wait for 1.1.* for the line below to start working
//See: https://github.com/aspnet/Announcements/issues/198
//options.Listener.AuthenticationManager.AllowAnonymous = true;
})
.Build();
host.Run();
Run Code Online (Sandbox Code Playgroud)
调用客户端配置如下
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
PreAuthenticate = true
};
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://TestServer:5000/");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Run Code Online (Sandbox Code Playgroud)
在我正在呼叫的服务中,我可以访问主叫用户的ClaimsPrincipal身份.
我的问题是如何使用通过CreateClient方法初始化的TestServer Client从集成测试中调用此服务.从集成测试调用时,确保设置标识的最佳方法是什么?
我也在使用XUnit,以防你想知道.
任何帮助或建议将不胜感激.
我正在使用FlurlHttp,并且想对某些API调用禁用AllowAutoRedirect。我知道如何使System.Net.Http.HttpClient不遵循302重定向?
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.AllowAutoRedirect = false;
HttpClient httpClient = new HttpClient(webRequestHandler);
// Send a request using GetAsync or PostAsync
Task<HttpResponseMessage> response = httpClient.GetAsync("http://www.google.com")
Run Code Online (Sandbox Code Playgroud)
但是对于Flurl,我只找到了与C#Flurl中所述类似的方法 -将WebRequestHandler添加到FlurlClient(我尚未编译下面的代码,因此可能会有一些错误)
public class HttpClientFactoryWithWebRequestHandler : DefaultHttpClientFactory
{
private readonly WebRequestHandler _webRequestHandler;
public HttpClientFactoryWithWebRequestHandler (WebRequestHandler webRequestHandler )
{
_webRequestHandler = webRequestHandler ;
}
public override HttpMessageHandler CreateMessageHandler()
{
var handler =_webRequestHandler ;
//Or var handler = new WebRequestHandler(_webRequestHandler );
return handler;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以为新的FlurlClient传递设置:
WebRequestHandler webRequestHandler = new …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过HTTP 2.0请求数据。我正在使用.Net Core 2.2中的HttpClient。我使用Windows 10,但将在生产环境中的Linux上运行。问题在于响应上的版本似乎总是“ 1.1”。我做错了什么?
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"),
"https://duckduckgo.com/"
))
{
request.Version = new Version(2, 0);
var response = await client.SendAsync(request);
Console.WriteLine(response.Version);
}
}
Run Code Online (Sandbox Code Playgroud) 我们正在HttpClient用来访问WebAPI另一台服务器上的主机。我们有一个MVC5应用程序,该应用程序正在从WebAPI带有IIS 8.5的窗口服务器2012 R2 获取数据
以下是用于从webapi获取数据的代码
//creating static instance of http client
private static HttpClient client = new HttpClient();
//static method to add common header
static ApiCall()
{
client.DefaultRequestHeaders.Add("Authorization",
string.Format("Value {0}", AppSettings.ApiSecurityKey));
client.DefaultRequestHeaders.ConnectionClose = true;
}
//finally posting data to the api
//objprop contains the data and other setting
string url = "apiurl";
var postContent = new StringContent(objprop.DataForPost,
System.Text.Encoding.UTF8, objprop.ContentType);
response = client.PostAsync(url, postContent).Result;
Run Code Online (Sandbox Code Playgroud)
但是在PT测试期间,我收到多个请求TIME_WAIT状态。因此,我们正在获得套接字异常。
使用HttpClient的最佳实践是什么?
使用后是否有任何可以释放插座的设置。
这里有类似的问题
1. 如何防止套接字/端口耗尽?
2. 为什么HttpClient会使套接字保持打开状态?
但这并没有帮助我。 …
c# ×5
.net-core ×2
asp.net-core ×2
redirect ×2
.net ×1
asp.net-mvc ×1
curl ×1
flurl ×1
http ×1
http-headers ×1
http-post ×1
http2 ×1
unit-testing ×1
websocket ×1
xunit ×1