标签: dotnet-httpclient

带有Autofac for Web API的HttpClient包装器

我继承了一个存根项目,它是一个HttpClient包装器,专门用于我们维护的API连接点.目的是将此解决方案作为nuget分发给需要使用API​​端点的其他.NET团队.

将Autofac电线连接看作下面的模块 - 我的问题是消费者会这样做:

var client = PlayersAPIHttpClientModule("http:/api.players.com");
Run Code Online (Sandbox Code Playgroud)

这个设置如何帮助消费者传递基URI然后访问GetPlayerInformation方法?

using Autofac;
using AutoMapper;
using Alpha.Domain.Players;
using System.Net.Http;

namespace Alpha.Clients.Players
{
    public class PlayersAPIHttpClientModule : Module
    {
        private readonly string _serviceBaseUrl;

        public PlayersAPIHttpClientModule(string serviceBaseUrl)
        {
            this._serviceBaseUrl = serviceBaseUrl;
        }

        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.Register(ctx =>
            {
                var serviceClient = new HttpClient 
                { 
                    BaseAddress = 
                    new System.Uri(this._serviceBaseUrl) 
                };

                return new 
                 PlayerDomainManager(serviceClient, 
                                     ctx.Resolve<IMappingEngine>());
            })
                .SingleInstance()
                .As<IPlayerDomainManager>();
        }
    }
}   
Run Code Online (Sandbox Code Playgroud)

这是与核心域共享的接口.

public interface IPlayerDomainManager
{
    IPlayer GetPlayerInformation (string playerId);
}
Run Code Online (Sandbox Code Playgroud)

这是具有公开方法功能的类本身. …

autofac c#-4.0 .net-4.5 dotnet-httpclient asp.net-web-api2

5
推荐指数
1
解决办法
2601
查看次数

如何使用 Dot-NET HttpClient 获取完整的 WWW-Authenticate 标头?

设想

我正在开发适用于 Windows Phone 8 的 Web 程序(我认为这并不重要)并使用Microsoft HTTP 客户端库

问题

当用户尝试获取 URL 时,我需要知道当响应是 401 时需要什么类型的身份验证。如果是 NTLM、Basic、Digest 等,这很容易;所有支持的WinHTTP方案。您可以使用以下代码来获取 URL:

HttpResponseMessage response;
using (var httpClient = new HttpClient(httpHandler))
{
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, authenticationUri);
     response = await httpClient.SendAsync(request, _cancelTokenSource.Token);
}
Run Code Online (Sandbox Code Playgroud)

检查需要哪种身份验证的最简单方法是使用该Headers.WwwAuthenticate.Contains方法,例如检查是否NTLM需要方案:

string scheme = "NTLM";
bool requiredScheme = response.Headers.WwwAuthenticate.Contains(new System.Net.Http.Headers.AuthenticationHeaderValue(scheme));
Run Code Online (Sandbox Code Playgroud)

如果scheme = "Bearer"然后它总是给假。

获取响应头

以下是在尝试访问需要Azure Active Directory身份验证的服务器时获得的。

杰森 Chrome 应用程序

使用Jason Chrome App 从网络服务器获取响应标头,我收到:

Pragma: no-cache
Date: Fri, …
Run Code Online (Sandbox Code Playgroud)

c# oauth azure www-authenticate dotnet-httpclient

5
推荐指数
0
解决办法
3871
查看次数

在POST方法,HttpClient中使用application/x-www-form-urlencoded

如果我要发送此数据怎么办:发布参数:

access_token access_token_Value

list数组数组(有4对arg)

arg1 arg1_value

arg2 arg2_value

arg3 arg3_value

arg4 arg4_value

在规范中是这样的(POST参数和返回数组中的所有可能的枚举值都在本文档中指定,并用竖线||分隔).我有通用Windows应用程序项目.如何将此数据转换为"application/x-www-form-urlencoded"格式?对于我使用的键值这样的普通对

    var body = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("arg1", "arg1value"),
        new KeyValuePair<string, string>("arg2", "arg2value"),
        new KeyValuePair<string, string>("arg3", "arg3value"),
        new KeyValuePair<string, string>("arg4", "arg4value")
    };

    var content = new FormUrlEncodedContent(body);
    var result = httpClient.PostAsync(uri, content).Result;
Run Code Online (Sandbox Code Playgroud)

这是好的(传输数据:arg1 = arg1value&arg2 = arg2value&....),但如果数据与我在本文开头写的相同怎么办?

c# dotnet-httpclient windows-phone-8 win-universal-app

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

我应该如何为dnx451和dnxcore50引用HttpClient?

我该如何HttpClient使用project.json文件引用?
我希望两个框架都可以工作:dnx451dnxcore50.

这是我目前对该project.json文件的尝试.(我删除了无关的部分.)

{
  "dependencies": {
    "Microsoft.Net.Http": "2.2.29",
    "Microsoft.Net.Http.Headers": "1.0.0-beta4",
    "System.Net.Http": "4.0.0-beta-22816"
  },
  "frameworks": {
    "dnx451": {
      "frameworkAssemblies": {
        "System.Net.Http": "4.0.0.0"
      }
    },
    "dnxcore50": { }
  }
}
Run Code Online (Sandbox Code Playgroud)

发现我列出的依赖项是一个试错法.

有了这个project.json文件,在dnxcore50上下文妥善解决了这个代码示例块中的所有类,但它未能解决HttpRequestMessage,HttpMethod以及MediaTypeWithQualityHeaderValuednx451背景:

var request = new HttpRequestMessage(HttpMethod.Get, "...");
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/..."));
var response = await client.SendAsync(request);
var model = await response.EnsureSuccessStatusCode().Content.ReadAsAsync<SomeModel>();
Run Code Online (Sandbox Code Playgroud)

.net c# dotnet-httpclient .net-core asp.net-core

5
推荐指数
1
解决办法
3221
查看次数

Microsoft OWIN测试服务器设置cookie

我有一个Owin测试服务器:

using (var testServer = TestServer.Create<TestPipelineConfiguration>())
using (var client = new HttpClient(testServer.Handler))
{
    client
        .DefaultRequestHeaders
        .Add("Cookie", $"{AspNetCookies}=HeyThere;");

    client.BaseAddress = new Uri("https://testserver/");

    var message = client
                    .PostAsync("print", new StringContent(
                                                jsonProvider.SerialiseObject(new
                                                {
                                                    Url = "https://some/url"
                                                }),
                                                Encoding.UTF8, "application/json"))
                    .Result;

    //var message = client.GetAsync("test").Result;

    message
        .StatusCode
        .ShouldBeEquivalentTo(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)

我想在那个cookie设置的其他属性,如HttpOnly,SecureDomain.

这可能吗?

c# dotnet-httpclient owin

5
推荐指数
1
解决办法
750
查看次数

为许多并发请求微调.NET ServicePoint

免责声明:我试图从人们的第一手经验中感受真实世界的数字.此时不需要实现细节/代码.

我们有web api,它将使用队列/消息代理将消息丢弃,然后,windows服务将读取队列以提供不同类型的http通知(简单地说:向许多网址/主机发送许多http请求).在窥视时间,这些数字可能是每秒数千.

考虑到ServicePoint最大连接限制加上ThreadPool线程,我试图找到正确的调整发送部分的措施.所以,潜在的问题是:

  1. 什么数量的并发http请求(最有可能通过HttpClient)听起来合理,每个Windows服务?
  2. 您在没有问题的项目中使用了哪些最大值?
  3. 如果为了完成高数字有一些特定的事情要注意,请指明它们.

笔记:

  • 目前,我并不关心队列/消息代理限制.为了讨论起见,我们可以假设这部分是无限的.

  • 这些请求非常轻量级,其中大部分都有几kbs的数据,因此预计响应时间非常短

.net architecture windows-services httpwebrequest dotnet-httpclient

5
推荐指数
0
解决办法
253
查看次数

如何获得dotnet Core 1.0找到System.Net.Http?

我有一个dotnet核心1.0应用程序,并尝试进行Post调用,但我遇到System.Net.Http的问题.我正在使用VSCode在OSX中开发这个应用程序.

当它尝试执行Post调用时,我在控制台中收到以下错误:

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: Could not load file or assembly 'System.Net.Http, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Run Code Online (Sandbox Code Playgroud)

我在依赖项列表末尾的project.json文件中添加了以下行,并在dotnet restore之后调用:

    "System.Net.Http": "4.1.0"
Run Code Online (Sandbox Code Playgroud)

这些是我的使用陈述:

using System;
using …
Run Code Online (Sandbox Code Playgroud)

dotnet-httpclient asp.net-core

5
推荐指数
0
解决办法
1230
查看次数

缺少HttpClient StatusDescription

我使用Microsoft.Net.Http(版本2.2.22)中的httpclient请求我的某些mvc页面。我的页面返回HttpStatusCodeResult,例如:

 return new HttpStatusCodeResult(clientResponse.StatusCode, "Blub Blub");
Run Code Online (Sandbox Code Playgroud)

使用httpclient时,调用页面不是问题。但是我找不到访问statusDescription(“ Blub Blub”)的方法。有没有访问描述的方法?如果不是,为什么Microsoft无法使它可访问?顺便说一句,如果我从浏览器(Chrome)调用该网站,说明将按预期显示。

c# asp.net asp.net-mvc dotnet-httpclient

5
推荐指数
1
解决办法
343
查看次数

通过REST API上传文件时,修正Artifactory中的校验和

我正在使用下面的代码通过Artifactory的REST API上传文件。我的问题是,当我通过GUI查看文件时,收到以下消息:

客户端未发布校验和值。如果您信任上载的工件,则可以通过单击“修复校验和”按钮来接受实际的校验和。

如何修复上传内容,以便此消息消失?

如果我通过GUI上传文件,则不提供校验和值,那么为什么在使用API​​时必须这样做?使用API​​修复校验和时,我可以调用额外的功能吗?

我还看到了此设置:https: //www.jfrog.com/confluence/display/RTF20/Handling+Checksums这与我的问题有关系吗?

string inFilePath = @"C:\temp\file.ext";
string inUrl = @"domain.com/repoKey/";
string username = "username";
string apiKey = "apikey";

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username+":"+apiKey)));

    using (var stream = File.OpenRead(inFilePath))
    {
        var response = client.PutAsync(inUrl + stream.Name, new StreamContent(stream));

        using (HttpContent content = response.Result.Content)
        {
            string data = content.ReadAsStringAsync().Result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

共有三种校验和和两组校验和组。

"checksums" : {
  "sha1" : "94332c090bdcdd87bd86426c224bcc7dc1c5f784",
  "md5" : "dcada413214a5bd7164c6961863f5111",
  "sha256" : "049c671f48e94c1ad25500f64e4879312cae70f489edc21313334b3f77b631e6"
},
"originalChecksums" : …
Run Code Online (Sandbox Code Playgroud)

c# artifactory dotnet-httpclient

5
推荐指数
2
解决办法
3319
查看次数

HttpClient和Unity的UnityWebRequest/WWW API之间的区别

Unity现在支持.NET 4.5,我可以使用命名空间中的HttpClientSystem.Net.Http.这很好,因为我有现有的客户端库,因此易于重用.

有谁知道使用单声道HttpClientUnity自己的网络之间的内部区别

我担心HttpClient不能针对不同的平台进行优化,因此可能会造成麻烦或变慢.

.net c# mono unity-game-engine dotnet-httpclient

5
推荐指数
1
解决办法
1829
查看次数