最初我的代码在每个请求的 using 语句中创建了一个新的 HttpClient 。然后我阅读了几篇关于重用 HttpClient 来提高性能的文章。
这是一篇这样的文章的摘录:
我不建议在 Using 块内创建 HttpClient 来发出单个请求。当 HttpClient 被释放时,它也会导致底层连接也被关闭。这意味着下一个请求必须重新打开该连接。您应该尝试重新使用您的 HttpClient 实例。
http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious
在我看来,只有当多个请求连续发送到同一个地方时,保持连接打开才有用 - 例如 www.api1.com。
我的问题是,我应该如何创建 HttpClients?
我的网站在后端讨论了大约十种不同的服务。
我应该创建一个 HttpClient 供所有人使用,还是应该为后端使用的每个域创建一个单独的 HttpClient?
示例:如果我与 www.api1.com 和 www.api2.com 交谈,我应该创建 2 个不同的 HttpClient,还是只创建一个 HttpClient?

我正在测试一个休息API帖子,当我在Postman上试用它时效果很好.但是,在某些情况下(与发布XML数据相关)如果我使用HttpClient API发布,我会收到以下错误:
"无法从传输连接读取数据:远程主机强行关闭现有连接."
但是相同的xml内容在Postman上工作正常,状态正常且响应正确.
任何人都知道使用C#HttpClient api和postman测试之间的区别是什么?如何配置我的api调用以匹配邮递员的行为?
这里我附上了源代码和Postman截图
public void createLoan()
{
string baseCreateLoanUrl = @"https://serverhost/create?key=";
var strUCDExport = XDocument.Load(@"C:\CreateLoan_testcase.xml");
using (var client = new HttpClient())
{
var content = new StringContent(strUCDExport.ToString(), Encoding.UTF8, Mediatype);
string createLoanApi = string.Concat(baseCreateLoanUrl, APIKey);
try
{
var response = client.PostAsync(createLoanApi, content).Result;
}
catch (Exception ex)
{
MessageBox.Show("Error Happened here...");
throw;
}
if (response.IsSuccessStatusCode)
{
// Access variables from the returned JSON object
string responseString = response.Content.ReadAsStringAsync().Result;
JObject jObj = JObject.Parse(responseString);
if (jObj.SelectToken("failure") == null)
{
// …Run Code Online (Sandbox Code Playgroud) 我正在使用VS15测试版并尝试使用WebClient.虽然引用了System.Net,并且intellisense建议WebClient类可用,但在构建时我收到以下错误:
命名空间'System.Net'中不存在类型或命名空间名称'WebClient'(您是否缺少程序集引用?)MyProj.ASP.NET Core 5.0 HomeController.cs
我正在做以下简单的代码:
var client = new System.Net.
var html = client.DownloadString(url);
Run Code Online (Sandbox Code Playgroud)
当我转到Web客户端的定义时,它向我展示了源代码.不太确定问题是什么 - WebClient移动了吗?我正在努力寻找解决方案.
谢谢!
从这个问题的答案:HttpClient和HttpClientHandler必须处理?,我发现最好的做法是不要处理System.Net.Http.HttpClient每个HTTP请求.特别指出:
HttpClient的标准用法是不要在每次请求后处理它.
这没关系.
我的问题是,这种"模式"是否也适用于此Windows.Web.Http.HttpClient?或者它应该按HTTP请求处理?我认为文档对此有点模糊.在其中一个样本中,它只是说明:
// Once your app is done using the HttpClient object call dispose to
// free up system resources (the underlying socket and memory used for the object)
httpclient.Dispose();
Run Code Online (Sandbox Code Playgroud)
我相信这可以通过两种方式阅读,因此对此有任何具体的意见.
我需要通过 HTTP 协议上传大文件(~200MB)。我想避免将文件加载到内存中并想直接发送它们。
多亏了这篇文章,我才能用HttpWebRequest.
HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create("....");
requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = WebRequestMethods.Http.Post;
requestToServer.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServer.KeepAlive = false;
requestToServer.ContentLength = ......;
using (Stream stream = requestToServer.GetRequestStream())
{
// write boundary string, Content-Disposition etc.
// copy file to stream
using (var fileStream = new FileStream("...", FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(stream);
}
// add some other file(s)
}
Run Code Online (Sandbox Code Playgroud)
但是,我想通过HttpClient. 我找到了描述使用 of 的文章,HttpCompletionOption.ResponseHeadersRead我尝试了类似的方法,但不幸的是它不起作用。
WebRequestHandler handler = new WebRequestHandler();
using …Run Code Online (Sandbox Code Playgroud) 我试图了解如何HttpClient在 Nop Commerce 中为 Captcha 实施,以及为了可测试性,如何HttpClient在 Nop Commerce 项目中管理创建新实例。
我遇到了ValidateCaptchaAttribute,ValidateCaptchaFilter我看到 HttpClient 已经被包裹在CaptchaHttpClient类中,但我不明白从哪里CaptchaHttpClient接收依赖HttpClient以及从哪里CaptchaHttpClient调用类的构造函数。
在ServiceCollectionExtensions课堂内,我看到以下代码:
public static void AddNopHttpClients(this IServiceCollection services)
{
//default client
services.AddHttpClient(NopHttpDefaults.DefaultHttpClient).WithProxy();
//client to request current store
services.AddHttpClient<StoreHttpClient>();
//client to request nopCommerce official site
services.AddHttpClient<NopHttpClient>().WithProxy();
//client to request reCAPTCHA service
services.AddHttpClient<CaptchaHttpClient>().WithProxy();
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到 HttpClient 对象是在哪里创建的:
var client = new HttpClient() // Where this is done?
Run Code Online (Sandbox Code Playgroud)
我可能错过了什么吗?
Nop 商务版 = 4.20
我正在开发 ASP.NET Core Web 应用程序,并且正在使用 Razor Pages。
我的应用程序中显示了一些 URL,当我单击其中一个 URL 时,我想将与该 URL 对应的文件下载到存储应用程序的服务器上的文件夹中,而不是客户端上。
这很重要,因为该文件需要由其他一些第三方应用程序在服务器端进行处理。
URL 以及其他元数据来自数据库,我创建了一个数据库上下文来加载它们。我制作了一个 CSS HTML 文件并以表单形式显示信息。当我单击按钮时,我将 URL 发布到方法处理程序。
我在方法中收到 URL,但我不知道如何在服务器上下载该文件,而不先在客户端上下载它,然后将其保存/上传到服务器。我怎样才能实现这个目标?
我有这个代码来加载 xml(到列表),它工作正常:
public MainPage()
{
this.InitializeComponent();
string XMLFilePath = Path.Combine(Package.Current.InstalledLocation.Path, "something.xml");
XDocument loadedData = XDocument.Load(XMLFilePath);
}
Run Code Online (Sandbox Code Playgroud)
如果我想从我的服务器调用 xml 怎么办!?
这是最后一次尝试:
using System.Net.Http;
using System.Runtime.Serialization.Json;
Run Code Online (Sandbox Code Playgroud)
...
private string jsonString;
public MainPage()
{
this.InitializeComponent();
loadData();
//string XMLFilePath = Path.Combine(Package.Current.InstalledLocation.Path, "something.xml");
XDocument loadedData = XDocument.Load(jsonString);
Run Code Online (Sandbox Code Playgroud)
...
private async void loadData()
{
var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://domain.com/something.xml"));
jsonString = await response.Content.ReadAsStringAsync();
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
An exception of type 'System.ArgumentNullException' occurred in System.Xml.ReaderWriter.dll but was not handled in user code …Run Code Online (Sandbox Code Playgroud) 使用Postman测试我的Web API时,我的API执行正常!
HttpClient在我的客户端应用程序中运行代码时,代码执行时没有错误,但在服务器上没有预期的结果.可能会发生什么?
从我的客户应用程序:
private string GetResponseFromURI(Uri u)
{
var response = "";
HttpResponseMessage result;
using (var client = new HttpClient())
{
Task task = Task.Run(async () =>
{
result = await client.GetAsync(u);
if (result.IsSuccessStatusCode)
{
response = await result.Content.ReadAsStringAsync();
}
});
task.Wait();
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
这是API控制器:
[Route("api/[controller]")]
public class CartsController : Controller
{
private readonly ICartRepository _cartRepo;
public CartsController(ICartRepository cartRepo)
{
_cartRepo = cartRepo;
}
[HttpGet]
public string GetTodays()
{
return _cartRepo.GetTodaysCarts();
}
[HttpGet]
[Route("Add")]
public string …Run Code Online (Sandbox Code Playgroud) 我从 ASP.NET MVC 控制器调用了这段代码:
protected string PostData(string url, ByteArrayContent content)
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromDays(1);
return client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将数据发布到需要一些时间来执行的 REST 服务,我会收到此错误:
System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: …Run Code Online (Sandbox Code Playgroud) c# ×9
.net ×2
asp.net-core ×2
uwp ×2
api ×1
asp.net-mvc ×1
httpclient ×1
nopcommerce ×1
postman ×1
razor-pages ×1
rest ×1
webclient ×1