Tag: dotnet httpclient

请求消息已发送。 无法多次发送相同的请求消息

我的代码在这里有什么问题吗? 我一直收到这个错误: System.InvalidOperationException:请求消息已发送。 无法多次发送相同的请求消息。 我的HttpRequestMessage在Func中,所以我想每次传入func()时都会得到一个全新的请求。 public async Task GetAsync(HttpRequestMessage request) { return await RequestAsync(() => request); } public async Task RequestAsync(Func func) { var response = await ProcessRequestAsync(func); if (response.StatusCode == HttpStatusCode.Unauthorized) { WaitForSomeTime(); response = await ProcessRequestAsync(func); } return response; } private async Task ProcessRequestAsync(Func func) { var client = new HttpClient(); var response […]

配置HttpClientFactory时出现证书错误

我需要在HttpClientFactory中添加证书。 使用HttpClient旧实现看起来像这样: var cookieContainer = new CookieContainer(); var handler = new HttpClientHandler { CookieContainer = cookieContainer }; var basePath = Directory.GetCurrentDirectory(); var certificatePath = Path.Combine(basePath, certPath); var fileExists = File.Exists(certificatePath); if (!fileExists) throw new ArgumentException(certificatePath); var certificate = new X509Certificate2(certificatePath, certPwd); handler.ClientCertificates.Add(certificate); using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); client.DefaultRequestHeaders.Add(“ApiKey”, apiKey); var body […]

如何在.NET Core中使用HttpClientHandler和HttpClientFactory

我想使用.NET Core 2.1中提供的HttpClientFactory ,但我还想在创建HttpClients时使用HttpClientHandler来利用AutomaticDecompression属性。 我很挣扎,因为.AddHttpMessageHandler接受DelegatingHandler而不是HttpClientHandler 。 有谁知道如何使这个工作? 谢谢,吉姆

HttpClient PostAsync发布空内容

我有一个api叫另一个。 这是我的代码,似乎导致世界另一边的ModelState.IsValid = false 。 var baseUri = new Uri(“http://localhost:5001/”): _httpClient.BaseAdress = baseUri; var data = new StringContent(content: model.Tostring(), encoding: Encoding.UTF8, mediaType: “application/json”); var response = await _httpClient.PostAsync(“api/product”, data); 在api上看Post([FromBody]Product product)我只看到product=null 。 更改为Post([FromBody]object product)也显示为null 。 从Postman那里打电话给api非常好。 将我的问题本地化为PostAsync 。 我的PostAsync什么? 编辑 : 我知道人们可能会建议PostAsJsonAsync ,但只有在我知道PostAsync的问题后PostAsync 。 🙁

无法从WinRT连接到远程服务器

我正在制作一个应用程序,基本上只需要将一段XML发送到服务器并返回。 我遇到了麻烦,但要让它工作并得到非常奇怪的错误 public bool Post(string data) { string server=”http://my-lan-computer:9091/foo” bool success = false; HttpClient client = new HttpClient(); try { client.PostAsync(server, new StringContent(data, Encoding.UTF8, “text/xml”)).Wait(); //error here success = true; } catch { } return success; } 我发布的服务器不是localhost,但它是我本地网络上的一台计算机。 我深深嵌套这个错误: innerException: {“An error occurred while sending the request.”} innerException: {“Unable to connect to the remote server”} […]

通过Rest c#httpClient创建jira问题

我在atlassian上看了一个答案https://answers.atlassian.com/questions/79902/using-httpclient-c-to-create-a-jira-issue-via-rest-generates-bad-request-response用户通过以下代码创建了JIRA问题。 我调整了它,但通过使用ObjectContent的自构建类问题得到错误 Http.HttpContent content = new Http.ObjectContent(data, jsonFormatter); 编译器不会接受它。 有人知道为什么吗? public string CreateJiraIssue() { string data= @”{ “”fields””: { “”project””: { “”key””: “”HELP”” }, “”summary””: “”Test Ticket””, “”description””: “”Creating of an issue using project keys and issue type names using the REST API””, “”issuetype””: { “”name””: “”Ticket”” }, “”assignee””: { “”name””: “”user”” } } }”; […]

如何正确调用ASP .NET MVC WebAPI 2方法

我为ASP.NET MVC WebAPI 2创建了分离项目,我想调用Register方法。 (我使用的项目默认是由VS2013创建的。) [Authorize] [RoutePrefix(“api/Account”)] public class AccountController : ApiController { …. // POST api/Account/Register [AllowAnonymous] [Route(“Register”)] public async Task Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityUser user = new IdentityUser { UserName = model.UserName }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) […]

C#:HttpClient,服务器提交了协议违规。 第= ResponseStatusLine

我正在使用HttpClient类与我的WPF应用程序中的Web服务进行通信。 当我在同一个连接上发出连续的GET请求时,一切正常。 但是,当我在同一连接上发出连续的PUT / PATCH请求时,第一个请求准确执行并且我收到响应,但第二个请求不包括请求中的正文,并且我收到臭名昭着的错误“服务器提交协议违规.Section = ResponseStatusLine“。 如果我在每次请求后通过添加Connection来手动关闭连接,我的请求会成功完成:靠近标题。 这种“解决方案”是一种糟糕的模式,性能无法适当扩展。 以下是我发送的请求的TCP流输出列表的抵押版本: Wireshark:遵循TCP流输出 GET /domain/api/tenant/current/object?objectName=Lizbot HTTP/1.1 Accept: application/json HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Content-Length: 50 {“Data”:[{“Id”:123,”ObjectName”:”Lizbot”,”Date”:null}],”Errors”:[]} PATCH /domain/api/tenant/current/object/123 HTTP/1.1 Accept: application/json Content-Type: application/json; charset=utf-8 Content-Length: 50 {“Id”:123,”ObjectName”:”Lizbot”,”Date”:null} HTTP/1.1 204 No Content Content-Type: application/json; charset=utf-8 {“Data”:null,”Errors”:[]} PATCH /domain/api/tenant/current/object/123/otherObject HTTP/1.1 Accept: application/json Content-Type: application/json; charset=utf-8 HTTP/1.1 400 Bad […]

检查与HttpClient的Internet连接

我很难理解波纹管代码如何处理偶尔的互联网连接丢失。 理想情况下,我想暂停应用程序,一旦连接丢失,并在它再次启动时恢复。 有关于如何做的指导方针吗? HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.UseDefaultCredentials = true; HttpClient client = new HttpClient(clientHandler) { MaxResponseContentBufferSize = 1000000 }; HttpResponseMessage response = await client.GetAsync(Url, ct);

WP8 HttpClient.PostAsync永远不会返回结果

我有一个Windows Phone 8应用程序,我正在调用等待HttpClient.PostAsync,它永远不会返回结果。 它只是坐在那里挂起。 如果我从控制台应用程序运行完全相同的代码,它几乎立即返回结果。 执行该工作的所有代码都驻留在可移植的类库中。 我很感激你能提供的任何帮助。 我在这个状态下发现的所有其他问题都使用await client.PostAsync,我已经在做了。 我的类库中的代码是这样的: public class Authenticator { private const string ApiBaseUrl = “http://api.fitbit.com”; private const string Callback = “http://myCallbackUrlHere”; private const string SignatureMethod = “HMAC-SHA1”; private const string OauthVersion = “1.0”; private const string ConsumerKey = “myConsumerKey”; private const string ConsumerSecret = “myConsumerSecret”; private const string RequestTokenUrl = […]