标签: dotnet-httpclient

C#Metro HttpClient未在PostAsync上接收cookie

我正在尝试使用.NET 4.5 HttpClient登录网站并接收cookie.我在离开试验之前就打破了,并检查了CookieContainer并且它不包含任何cookie.响应发回200状态.

private async void Login(string username, string password)
{
    try
    {
        Uri address = new Uri(@"http://website.com/login.php");
        CookieContainer cookieJar = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler()
        {
            CookieContainer = cookieJar
        };
        handler.UseCookies = true;
        handler.UseDefaultCredentials = false;
        HttpClient client = new HttpClient(handler as HttpMessageHandler)
        {
            BaseAddress = address
        };

        HttpContent content = new StringContent(string.Format("username={0}&password={1}&login=Login&keeplogged=1", username, password));
        HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);
    }
Run Code Online (Sandbox Code Playgroud)

我不知道为什么这不起作用.当我尝试.NET 4风格时它工作正常.

c# microsoft-metro windows-8 .net-4.5 dotnet-httpclient

4
推荐指数
1
解决办法
5505
查看次数

HttpClient PostAsync to Blogger API

我使用以下API来允许我与Google Blogger进行互动.我需要在用户博客中插入帖子.但是我的PostAsync功能有问题.我得到401告诉我,尽管有API密钥,我的请求仍未获得授权,但我认为我可能无法正确插入我的OAuth令牌.

我有以下代码,

这是我设置授权标题的代码,(注意密钥有假,但与我认为的OAuth令牌相同)

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ya29.AHES6ZTBZi1dWPVdlcF7qAD-nSM6XxwY2323232m4lXW");
Run Code Online (Sandbox Code Playgroud)

这是我的PostAsync功能

                HttpResponseMessage response = await req.PostAsync(URLs.postBlogURL + blogID + URLs.postBlogURLPost, new StringContent(json));
Run Code Online (Sandbox Code Playgroud)

谁能告诉我哪里出错了?干杯.

[ 更新 ]

我不确定授权是否必须在其中包含字符串承载.

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer ya29.AHES6ZTBZi1dWPVdlcF7qAD-nSM6XxwY2323232m4lXW");
Run Code Online (Sandbox Code Playgroud)

c# rest blogger oauth dotnet-httpclient

4
推荐指数
1
解决办法
1万
查看次数

如何在使用模拟HttpMessageHandler时使用HttpClient管理cookie

我有一个单元测试,通过传入HttpRequestMessage实例和接收HttpResponseMessages实例来调用类库.这与ApiController在这方面测试WebApi非常相似.

我正在测试的代码添加了cookie HttpResponseMessage,并希望在后续的来电中看到这些cookie HttpRequestMessage,这就是浏览器(或HttpWebRequest)的行为方式.

我没有使用,HttpClientHandler因为请求实际上不是在网络上发送,而是使用HttpMessageHandler我初始化HttpClientwith 的模拟传递给产品.因此HttpClientHandler我无法访问cookie处理.似乎要获得我需要的cookie行为,我将不得不手动解析其中的cookie HttpResponseMessage,然后手动将它们序列化为HttpRequestMessage.这完全省略了CookieContainer正确应用cookie到正确请求的逻辑.

有没有更简单的方法?

mocking httpcookie dotnet-httpclient

4
推荐指数
1
解决办法
1115
查看次数

处理注入的HttpClient

我们的MVC应用程序使用HttpClient调用WebAPI操作.我决定使用StructureMap注入HttpClient并在控制器中覆盖dispose

public HomeController(HttpClient httpClient)
{
    _httpClient = httpClient;
}

protected override void Dispose(bool disposing)
{
   if (disposing && _httpClient != null)
   {
       _httpClient.Dispose();
   }
   base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)

StructureMap ObjectInitialize基本上看起来像这样..

x.For<HttpClient>().Use(() => new HttpClient() { BaseAddress = "my/uri/"});
Run Code Online (Sandbox Code Playgroud)

当我构建它时,CodeAnalysis会抱怨"Dispose objects before losing scope"并指向IoC代码.

我可以抑制它,或者我需要在何处处理HttpClient?我也试过了

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
Run Code Online (Sandbox Code Playgroud)

但我仍然违反规则.

structuremap dependency-injection asp.net-mvc-4 asp.net-web-api dotnet-httpclient

4
推荐指数
1
解决办法
1726
查看次数

System.Net.Http.Formatting库的PCL重新包装中的ReadAsAsync <>

尝试在System.Net.Http.Formatting的Bitrium.Http.Extensions重新包装中调用ReadAsAsync <>扩展方法时,我收到以下错误.

程序集'System.Net.Http.ObjectContent'中的方法'SerializeToStreamAsync'来自程序集'Bitrium.Http.Extensions,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = 43390f7aed073600'没有实现.

我在PCL项目中有类似于以下代码的东西,我通过简单的单元测试进行测试.我没有实现await模式,但我不相信它与此相关.

public class RestApi()
{
    public void Get()
    {
        HttpResponseMessage response = new HttpResponseMessage();
        HttpClient client = new HttpClient();
        response = client.GetAsync("http://someUrl.com").Result;
        var modelList = response.Content.ReadAsAsync<List<Model>>().Result; // I get the exception here
     }
}
Run Code Online (Sandbox Code Playgroud)

对方法的调用:

var target = new RestApi();
target.Get();
Run Code Online (Sandbox Code Playgroud)

在这一点上我能做些什么吗?我不一定需要Async功能,所以另一个仍然将我的响应转换为我的模型的实现也可以.

c# rest json.net portable-class-library dotnet-httpclient

4
推荐指数
1
解决办法
1515
查看次数

创建HttpClient辅助方法的问题

我有一个功能异步的任务调用Web服务:

private async Task GetResult()
{
   using (var client = new HttpClient())
   {
      client.BaseAddress = new Uri(_baseAddress);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));
      client.DefaultRequestHeaders.Add("Username", _username);
      client.DefaultRequestHeaders.Add("Action", "GET");
      /* etc */
      var response = await client.GetAsync(client.BaseAddress);
   }
}
Run Code Online (Sandbox Code Playgroud)

我想分离出HttpClient对象的创建,以便可以参数化和重用:

private async Task GetResult()
{
   using (var client = GetClient(_baseAddress, _username))
   {
      var response = await client.GetAsync(client.BaseAddress);
   }
}
private static HttpClient GetClient(string Address, string Username)
{
   using (var client = new HttpClient())
   {
      client.BaseAddress = new Uri(Address);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));
      client.DefaultRequestHeaders.Add("Username", Username); …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient

4
推荐指数
1
解决办法
935
查看次数

HttpClient GetAsync ThreadPool Starvation

我们有一个面向微服务的后端堆栈.所有的微服务都建立Nancy在windows服务之上并注册为windows服务topshelf.

处理大多数流量(~5000 req/s)的服务之一,在8个服务器中的3个服务器上开始出现线程池饥饿问题.

这是我们遇到特定端点时遇到的异常:

System.InvalidOperationException: There were not enough free threads in the ThreadPool to complete the operation.
   at System.Net.HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)
   at System.Net.Http.HttpClientHandler.StartGettingResponse(RequestState state)
   at System.Net.Http.HttpClientHandler.StartRequest(Object obj)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at RandomNamedClient.<GetProductBySkuAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ProductService.<GetBySkuAsync>d__3.MoveNext() in ...\ProductService.cs:line 34
--- End …
Run Code Online (Sandbox Code Playgroud)

c# threadpool async-await nancy dotnet-httpclient

4
推荐指数
1
解决办法
1029
查看次数

Xamarin需要引用Windows.Foundation.FoundationContract

我在Visual Studio 2015更新2中使用Xamarin创建了一个新的iPhone(iOs 9.3)应用程序.我在Mac上有Xamarin beta频道(有Xcode等)

我有这个代码:

using Windows.Web.Http;
...
private async void GetPois()
{
    var client = new HttpClient();
    var response = await client.GetAsync(new Uri("http://onlinesource/json"));
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是GetAsync我没有安装httpclient nuget,因为它抛出了一个错误.

将ref添加到程序集Windows.Foundation.FoundationContract

已经ModernHttpClient安装了nuget,但没有使用它.@Andrii Krupka是的我也using System; 添加了System.Net.Http而不是Windows现在我找不到类型或命名空间.添加了对system.net和system.net.http的引用,现在它可以工作了.接下来要解决的问题是禁用ats.将此标记为@SushiHangover的回答,谢谢大家!

c# xamarin.ios dotnet-httpclient xamarin

4
推荐指数
1
解决办法
2096
查看次数

使用HttpClient,发送没有架构的授权令牌

注意:这个问题类似于这一个,但其建议的答案在这里并不适用.

我正在尝试访问此API,它正在寻找一个如下所示的标头:

Authorization: {token}
Run Code Online (Sandbox Code Playgroud)

请注意,没有任何身份验证方案.

我试过做:

myHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("", authToken);
Run Code Online (Sandbox Code Playgroud)

这导致了一个ArgumentException,说我无法传递一个空字符串.

我也试过了两个:

myHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authToken);
Run Code Online (Sandbox Code Playgroud)

myHttpClient.DefaultRequestHeaders.Add("Authorization", authToken);
Run Code Online (Sandbox Code Playgroud)

这两个都导致FormatException.

似乎有些东西迫使我遵循我的授权标头的标准格式,但我尝试访问的服务不使用该标准格式.

c# asp.net-web-api dotnet-httpclient

4
推荐指数
2
解决办法
3467
查看次数

配置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 = new { UserName = username, UserPassword = password };
    var jsonBody = JsonConvert.SerializeObject(body);
    var content = new StringContent(jsonBody, Encoding.UTF8, contentType);

    var …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient .net-core httpclientfactory

4
推荐指数
1
解决办法
1208
查看次数