标签: dotnet-httpclient

ASP.NET Web API消息处理程序

是否可以控制自定义消息处理程序的执行顺序?

作为一个例子,我可能希望首先执行日志记录处理程序,因此我总是记录一个请求.

除了最后添加日志记录处理程序,我没有看到如何实现这一点.

config.MessageHandlers.Add(new CustomHandlerOne()); 
config.MessageHandlers.Add(new CustomHandlerTwo());
config.MessageHandlers.Add(new LoggingHandler());
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api dotnet-httpclient

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

无法从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;

    }
Run Code Online (Sandbox Code Playgroud)

我发布的服务器不是localhost,但它是我本地网络上的一台计算机.我深深嵌套这个错误:

innerException: {"An error occurred while sending the request."}

innerException: {"Unable to connect to the remote server"}

innerException: {"An attempt was made to access a socket in a way forbidden by its access permissions 123.123.123.123:9091"}
Run Code Online (Sandbox Code Playgroud)

我的应用程序具有Internet客户端功能.我可以通过其他商店应用访问我的本地网络和互联网.我可以在firefox中访问资源获得正确的行为.我没有启用防火墙,也没有阻止这些端口的防病毒软件

什么可能导致这个模糊的错误?我该如何解决?

.net c# networking windows-runtime dotnet-httpclient

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

使用HttpMethod的自定义值

我正在使用HttpClient,我需要设置非标准类型HttpMethod.如果使用HttpWebRequest只需要一个字符串,那么HttpClient期望一个HttpMethod.枚举可用值HttpMethod,我没有看到添加自定义值的方法.有什么想法吗?

c# http-method dotnet-httpclient

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

为什么304响应没有更新本地缓存资源的新鲜度?

当我执行条件GET并获得具有Cache-Control max-age头的304响应时,我期望更新资源的新鲜度以及将来从本地缓存获取表示的请求(假设它是新鲜的).但是,我无法使用HttpClient来实现此功能.

这是我的复制,作为一个简单的.net 4.5控制台应用程序使用Nuget依赖项Microsoft.AspNet.WebApi.OwinSelfHostMicrosoft.Net.Http.

using System;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;

namespace TestEtag
{
    class Program
    {
        static void Main(string[] args)
        {
            // Run as administrator to allow web server to start.
            // Clear browser cache to see initial 200 response when running multiple times

            var host = String.Format("http://{0}:8080/", Environment.MachineName);
            var server = WebApp.Start(host, app =>
            {
                var config = new HttpConfiguration();
                config.MapHttpAttributeRoutes();
                app.UseWebApi(config);
            }); …
Run Code Online (Sandbox Code Playgroud)

caching http dotnet-httpclient

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

使用Uri字符串,可能有也可能没有尾随/

我已经在代码中使用HttpClient一段时间了,并且一直觉得它的使用Uris导致了我的实现中的一些脆弱性.我们的大多数服务端点基地址都在app./web.config中.结果,它们可以很容易地改变.

我发现当使用这些端点字符串生成a时Uri,如果它们不以a结尾/,我会得到非常不稳定的行为.当调用GetAsync()与非/封端的BaseAddress,即常发送的GET请求所得级联URL后最终下降任一字符串/中的BaseAddress,或者它会下降字符串前述第一/在GetUri.

例如:

BaseAddress: http://test/serviceEndpoint

GetUri: api/customer

HttpClient.GetAsync()GetUri它调用时,它将尝试从中获取http://test/api/customer.如果我BaseAddress用a 封顶/,一切都按预期工作.

我的问题BaseAddress配置驱动,并在.config文件中添加注释,说"请确保使用/!结束所有服务URL ".是一个非常脆弱的解决方案.

所以我养成了在我的所有HttpClient构造中使用以下代码的习惯:

        var service = settings.GetValue("ServiceBaseUrl");
        var serviceUri = !service.EndsWith("/")
            ? new Uri(service + "/")
            : new Uri(service);

        _client = new HttpClient
        {
            BaseAddress = serviceUri
        };`
Run Code Online (Sandbox Code Playgroud)

虽然这不易碎,但在每个HttpClient构造函数中都有重复性.是否有任何东西HttpClientUri …

c# uri dotnet-httpclient

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

c#httpclient PostAsJson发送GET请求而不是POST

我正在使用HttpClient发布帖子请求.我不回来405方法.在fiddler中捕获跟踪时,它会以GET而不是POST的形式出现!

using (var client = new HttpClient())
            {
                var url = AppSettingsUtil.GetString("url");
                var response = client.PostAsJsonAsync(url, transaction).Result;
            }
Run Code Online (Sandbox Code Playgroud)

我知道异步/等待问题.这是一个简化的示例来说明问题.

是否存在可能影响此问题的某种web.config或machine.config设置?其他请求(通过RestSharp发送)正确发送帖子

这是小提琴手捕获的内容.在fiddler中重新运行跟踪也会返回405(如预期的那样).手动将其切换到POST并从fiddler运行.

另外,也许是因为该方法被切换到GET,在fiddler中没有捕获到的身体,我不得不手动粘贴在JSON中

GET /*URL*/ HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: /*host*/
Connection: Keep-Alive
Run Code Online (Sandbox Code Playgroud)

c# json http httpclient dotnet-httpclient

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

如何在HttpClient中使用Ninject

使用Ninject向应用程序中的所有Controller实例注入相同的HttpClient对象的推荐方法是什么?

当前,我在Adam Freeman的MVC书之后注入EntityFramework数据库上下文,如下所示。但是,这会为每个控制器实例创建一个新的dbContext,这对于HttpClient可能不是理想的,因为HttpClient旨在在MVC应用程序中的所有控制器之间重用。

构造函数:

public class AccountController : Controller
{
  MyDBContext dbContext = new MyDBContext();

  public AccountController(MyDBContext context)
  {
    dbContext = context;
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

Ninject工厂如下:

/// Class based on Adam Freeman's MVC book to use dependency injection to create controllers
public class NinjectControllerFactory : DefaultControllerFactory
{
  private IKernel ninjectKernel;

  public NinjectControllerFactory()
  {
    ninjectKernel = new StandardKernel();
    AddBindings();
  }

  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  {
    return controllerType == null
      ? null
      : (IController)ninjectKernel.Get(controllerType);
  }

  private void AddBindings()
  { …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc ninject dotnet-httpclient

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

HttpClient解码编码的网址?

我试图找出在HttpClient处理URL方面的一些不一致之处。

我有以下测试代码:

public async Task TestHttpClient()
{
    var baseUrl = "https://api.twitter.com/1.1/search/tweets.json";
    //var query = "(cafe OR boulangerie)";
    var query = "(café OR boulangerie)";

    var url = baseUrl + $"?q={Uri.EscapeDataString(query)}";

    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(url);

    await response.Content.ReadAsStringAsync();
}
Run Code Online (Sandbox Code Playgroud)

该代码实际上将无法工作,因为我们需要身份验证和其他内容才能进行Twitter搜索。但这证明了我的问题。

该变量url将具有以下值: https://api.twitter.com/1.1/search/tweets.json?q=%28caf%C3%A9%20OR%20boulangerie%29

但是,查看Fiddler中的请求,我可以看到实际发送的是: https://api.twitter.com/1.1/search/tweets.json?q=(caf%C3%A9%20OR%20boulangerie)

因此突然之间,括号不再被编码。这对我来说很重要,因为我使用编码的查询字符串来计算用于对Twitter进行身份验证的签名。因此,我的签名将带有百分比编码的括号,而请求不会,因此Twitter引发错误并告诉我身份验证失败。

有趣的是,如果我使用常规e而不是常规发送查询,é则括号将编码在请求中!像这样:https://api.twitter.com/1.1/search/tweets.json?q=%28cafe%20OR%20boulangerie%29

我想这是某种错误HttpClient吗?我可以以某种方式解决此问题吗?

c# encoding url-encoding dotnet-httpclient .net-core

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

如何知道任意标头名称作为请求标头,内容标头或两者都无效?

考虑以下代码:

if (request.Headers.Contains(headerName))
    ...
Run Code Online (Sandbox Code Playgroud)

其中requestSystem.Net.Http.HttpRequestMessage的实例.headerName相当随意; 我们假设它来自用户输入.如果它的值恰好是"Content-Type",则抛出异常:

System.InvalidOperationException:未使用的标头名称.确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用.

我究竟如何"确定"这一点?该Headers集合在内部知道允许哪些标题名称,并且此列表request.Headers与其不同request.Content.Headers.看来我有2个选项来验证任意字符串:

  1. 根据BCL文档或源代码,保持自己的"白名单"进行验证.
  2. 使用try/catch逻辑.

这些方法都不是理想的.有没有办法利用已经包含的知识System.Net.Http来执行此验证?

c# http dotnet-httpclient

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

ASP.NET Core 2从HttpResponseMessage获取Cookie

目前,我正在使用ASP.NET Core 2编写一个项目,并且正在尝试从第三方网站获取JSON文件。问题在于该网站需要一些Cookie才能从中检索数据。我在Startup.cs文件中实现了一个键入的HttpClient,如下所示:

    services.AddHttpClient<IMyClient, MyClient>().ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            UseCookies = true,
            UseDefaultCredentials = true,
            CookieContainer = new CookieContainer()
        };
    });
Run Code Online (Sandbox Code Playgroud)

有什么方法可以访问CookieContainer来使用CookieContainer.GetCookies()方法,以便可以从HttpResponseMessage复制各种Cookie,例如会话Cookie和一些验证令牌?

抱歉,如果我做错了,这是我的第一篇文章。

编辑

通过在请求管道中添加HttpMessageHandler使其工作

services.AddHttpClient<IMyHttpClient, MyHttpClient>()
                    .AddHttpMessageHandler<MyMessageHandler>();
Run Code Online (Sandbox Code Playgroud)

并在HttpMessageHandler中编辑http标头信息

public class MyMessageHandler : DelegatingHandler
{
    private readonly CookieContainer _cookies;

    public MyMessageHandler()
    {
        _cookies = new CookieContainer();
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken cancellationToken)
    {
        try
        {
            if (_cookies.Count == 0 && message.RequestUri.Host.Contains("example.com"))
            {
                // Simulate the Request
                var getCookieMesssage = new HttpRequestMessage()
                {
                    RequestUri = new …
Run Code Online (Sandbox Code Playgroud)

c# cookies dotnet-httpclient asp.net-core-2.1 httpclientfactory

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