HttpRequestMessage.Properties的目的是什么?
我想知道它是否为我的应用程序提供了一些有用的东西.
我正在使用它System.Net.Http.HttpClient做一些客户端HTTP通信.我在一个地方得到了所有的HTTP,从其余的代码中抽象出来.在一个实例中,我想将响应内容作为流读取,但是流的使用者与HTTP通信发生的位置以及流被打开的情况很好地隔离.在负责HTTP通信的地方我处理所有的HttpClient东西.
此单元测试将失败Assert.IsTrue(stream.CanRead):
[TestMethod]
public async Task DebugStreamedContent()
{
Stream stream = null; // in real life the consumer of the stream is far away
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.google.com/", UriKind.Absolute);
using (var request = new HttpRequestMessage(HttpMethod.Get, "/"))
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
//here I would return the stream to the caller
stream = await response.Content.ReadAsStreamAsync();
}
Assert.IsTrue(stream.CanRead); // FAIL if response is disposed so is the stream …Run Code Online (Sandbox Code Playgroud) 我正在使用其托管页面集成与Alternative Payments进行集成.他们的C#SDK暂时没有这种集成,但正如你所看到的那样非常简单,我发了一个小类来发送post请求并获得JSON响应.
我测试了我在PostMan和cURL上发送的json对象,两者都工作,也是认证头,所以我认为它们不是问题.这是我班级的构造函数:
public AlternativePaymentsCli(string apiSecretKey)
{
this._apiSecretKey = apiSecretKey;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var authInfo = _apiSecretKey;
authInfo = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:", _apiSecretKey)));
// The two line below because I saw in an answer on stackoverflow.
_httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
_httpClient.DefaultRequestHeaders.Add("Keep-Alive", "3600");
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Anything.com custom client v1.0");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
}
Run Code Online (Sandbox Code Playgroud)
以及我发布数据的方法:
public string CreateHostedPageTransaction(HostedPageRequest req)
{
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
// I send this same json content on …Run Code Online (Sandbox Code Playgroud) 我注意到当我使用System.Net.HttpClient短暂的超时时,它有时可能会使进程崩溃,即使它被包装在try-catch块中也是如此.这是一个重现这个的简短程序.
public static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
{
tasks.Add(MakeHttpClientRequest());
}
Task.WaitAll(tasks.ToArray());
}
private async static Task MakeHttpClientRequest()
{
var httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) };
var request = "whatever";
try
{
HttpResponseMessage result =
await httpClient.PostAsync("http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=766c0ac7802d55314fa980727f747710",
new StringContent(request));
await result.Content.ReadAsStringAsync();
}
catch (Exception x)
{
Console.WriteLine("Error occurred but it is swallowed: " + x);
}
}
Run Code Online (Sandbox Code Playgroud)
运行此命令会使进程崩溃,但会出现以下异常:
Unhandled Exception: System.AggregateException: One …Run Code Online (Sandbox Code Playgroud) 在为Windows开发.NET 4.5桌面应用程序时,我习惯使用System.Net.Http.HttpClient后端Web API进行所有通信.我现在正在开发一个Windows应用商店应用程序并注意到它的存在Windows.Web.Http.HttpClient.我已经找到了两个客户之间的主要区别但没有运气的信息.
从MSDN我知道我应该开始Windows.Web.Http.HttpClient在我的Windows应用商店应用中使用,因为System.Net.Http.HttpClient可能会从API中删除:
注意 System.Net.Http和System.Net.Http.Headers命名空间可能在Windows的未来版本中不可用,以供Windows应用商店应用使用.从Windows 8.1和Windows Server 2012 R2开始,使用Windows.Web.Http命名空间中的Windows.Web.Http.HttpClient和相关的Windows.Web.Http.Headers和Windows.Web.Http.Filters命名空间代替Windows运行时应用程序.
但除了这些信息之外,我很难弄清楚主要区别是什么,使用的主要好处是Windows.Web.Http.HttpClient什么?它添加了什么,我们还没有进入System.Net.Http.HttpClient?
非常感谢官方文档支持的答案.
我到处都可以看到在 DI 中创建客户端的三种主要方法(基本的、命名的、类型化的),但我找不到注入IHttpClientFactory或HttpClient(两者都可能)的地方。
Q1 : 注射IHttpClientFactory或HttpClient请有什么区别?
Q2:如果IHttpClientFactory被注入,我应该factory.CreateClient()在每次调用时使用吗?
给出以下代码:
var cts = new CancellationTokenSource();
try
{
// get a "hot" task
var task = new HttpClient().GetAsync("http://www.google.com", cts.Token);
// request cancellation
cts.Cancel();
await task;
// pass:
Assert.Fail("expected TaskCanceledException to be thrown");
}
catch (TaskCanceledException ex)
{
// pass:
Assert.IsTrue(cts.Token.IsCancellationRequested,
"expected cancellation requested on original token");
// fail:
Assert.IsTrue(ex.CancellationToken.IsCancellationRequested,
"expected cancellation requested on token attached to exception");
}
Run Code Online (Sandbox Code Playgroud)
我希望ex.CancellationToken.IsCancellationRequested是true在catch块内,但事实并非如此.我误会了什么吗?
.net c# async-await cancellationtokensource dotnet-httpclient
我有一些文件要上传,一些文件失败,因为帖子是异步的而不是同步的..
我正在尝试将此调用作为同步调用..
我想等待回应.
如何将此调用设为同步?
static async Task<JObect> Upload(string key, string url, string
sourceFile, string targetFormat)
{
using (HttpClientHandler handler = new HttpClientHandler {
Credentials = new NetworkCredential(key, "")
})
using (HttpClient client = new HttpClient(handler))
{
var request = new MultipartFormDataContent();
request.Add(new StringContent(targetFormat), "target_format");
request.Add(new StreamContent(File.OpenRead(sourceFile)),
"source_file",
new FileInfo(sourceFile).Name);
using (HttpResponseMessage response = await client.PostAsync(url,
request).ConfigureAwait(false))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync().ConfigureAwait(false);
return JsonObject.Parse(data);
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏!
我是 docker 新手,我有一个包含 2 个 dotnet 核心项目的 Visual Studio 解决方案 - UI 和 API。我已经为这两个项目添加了 docker 支持,并且在我调试时它们都可以正常工作。现在他们有一个 http 客户端可以从网络调用 api,但它突然开始给出“无法分配请求的地址”错误。
奇怪的是,这个错误只出现在一台电脑上。我有第二台电脑,仍然可以顺利运行项目。其他团队成员都没有看到此错误。
我已经修剪了所有容器和图像,但这没有帮助。我没有使用 docker-compose,所以我在相关问题上找到的答案对我不起作用。
这里的文章解释了 localhost 在 docker 中如何以不同的方式解释,但我不确定如何使他的解决方案为我工作。
事实上,这个问题在其他电脑上没有发生,这才是真正让我困惑的地方。
注意:我不确定需要共享代码的哪一部分,因为我不知道与此问题相关的内容。
dotnet-httpclient docker .net-core docker-compose asp.net-core
我很好奇这HttpClientFactory堂课的目的是什么.没有描述MSDN上存在的原因(参见链接).
有些Create方法有更专业的参数,但大多数我不知道没有参数的调用和普通的构造函数之间有什么区别.
var httpClient = HttpClientFactory.Create();
Run Code Online (Sandbox Code Playgroud)
VS
var httpClient = new HttpClient();
Run Code Online (Sandbox Code Playgroud)
在大多数示例中,我看到使用了new HttpClient(),没有任何using语句,即使HttpClient该类派生自IDisposable.
由于HttpClient该类源自IDisposable,工厂是否有一些池化或缓存?是否有性能优势,或者无关紧要?
c# ×8
.net ×5
asp.net-core ×2
.net-core ×1
asp.net ×1
async-await ×1
docker ×1
httpresponse ×1
idisposable ×1
json ×1
stream ×1