标签: flurl

使用Flurl发布多个标头

嗨,我正在使用Flurl,我需要为帖子设置多个标题,并且网站上的文档状态等待url.WithHeaders(new {h1 ="foo",h2 ="bar"}).GetJsonAsync();

我不确定这意味着什么,什么是H1,H2?

我正在尝试设置Headers"API-VERSION:21"和"Authorization:askjdalksdjlaksjdlaksjd";

谢谢

c# flurl

6
推荐指数
1
解决办法
3225
查看次数

获得响应标题

使用Flurl从API获取响应.

var response = await url.WithClient(fc)
            .WithHeader("Authorization", requestDto.ApiKey)
            .GetJsonAsync<T>();
dynamic httpResponse = response.Result;
Run Code Online (Sandbox Code Playgroud)

但我无法访问httpResponse.Headers

如何在使用GetJsonAsync时访问响应标头.

c# .net-core flurl

6
推荐指数
1
解决办法
1909
查看次数

如何更改FLURL客户端的HTTP请求内容类型?

我正在使用flurl提交HTTP请求,这非常有用.现在我需要将一些请求的" Content-Type"标题更改为"application/json; odata = verbose"

    public async Task<Job> AddJob()
    {

        var flurlClient = GetBaseUrlForGetOperations("Jobs").WithHeader("Content-Type", "application/json;odata=verbose");
        return await flurlClient.PostJsonAsync(new
        {
            //Some parameters here which are not the problem since tested with Postman

        }).ReceiveJson<Job>();
    }

    private IFlurlClient GetBaseUrlForOperations(string resource)
    {
        var url = _azureApiUrl
            .AppendPathSegment("api")
            .AppendPathSegment(resource)
            .WithOAuthBearerToken(AzureAuthentication.AccessToken)
            .WithHeader("x-ms-version", "2.11")
            .WithHeader("Accept", "application/json");
        return url;
    }
Run Code Online (Sandbox Code Playgroud)

你可以看到我试图在上面添加标题(.WithHeader("Content-Type", "application/json;odata=verbose"))

不幸的是,这给了我以下错误:

"InvalidOperationException:Misused header name.确保请求头与HttpRequestMessage一起使用,响应头与HttpResponseMessage一起使用,内容头与HttpContent对象一起使用."

我也尝试了flurl的"ConfigureHttpClient"方法,但无法找到设置内容类型标头的方式/位置.

c# http-headers flurl

6
推荐指数
2
解决办法
5453
查看次数

使用 Flurl 发布“multipart/form-data”

我需要发布以下请求:

POST http://target-host.com/some/endpoint HTTP/1.1
Content-Type: multipart/form-data; boundary="2e3956ac-de47-4cad-90df-05199a7c1f53"
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Content-Length: 6971
Host: target-host.com

--2e3956ac-de47-4cad-90df-05199a7c1f53
Content-Disposition: form-data; name="some-label"

value
--2e3956ac-de47-4cad-90df-05199a7c1f53
Content-Disposition: form-data; name="file"; filename="my-filename.txt"

<file contents>
--2e3956ac-de47-4cad-90df-05199a7c1f53--
Run Code Online (Sandbox Code Playgroud)

我可以使用 Pythonrequests库轻松完成此操作,如下所示:

import requests

with open("some_file", "rb") as f:
    byte_string = f.read()

requests.post(
    "http://target-host.com/some/endpoint",
    data={"some-label": "value"},
    files={"file": ("my-filename.txt", byte_string)})
Run Code Online (Sandbox Code Playgroud)

有没有办法对Flurl.Http图书馆做同样的事情?

我的文档记录方式的问题是它将Content-Type为每个键值对插入filename*=utf-8''标头,并为文件数据插入标头。但是,我尝试向其发布请求的服务器不支持此功能。还要注意标题中namefilename值周围的双引号。

编辑:下面是我用来发出帖子请求的代码Flurl.Http

using System.IO;
using Flurl;
using Flurl.Http;

namespace ConsoleApplication
{
    public class Program
    { …
Run Code Online (Sandbox Code Playgroud)

c# post multipartform-data flurl

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

使用 FlurlClient 的自定义 HttpClientHandler 不使用 ClientCertificate

我需要向我的 Web 请求添加一个客户端证书并尝试以这种方式实现它: Stackoverflow

在此答案的末尾,介绍了“FlurlClient 方式”。使用和配置 FlurlClient 而不是全局 FlurlHttp 配置。我试过这个,但没有用。

我创建了一个新的.NET Core控制台应用程序来向您展示问题:

static void Main(string[] args)
{
   /****** NOT WORKING *******/
   try
   {
      IFlurlClient fc1 = new FlurlClient(url)
         .ConfigureClient(c => c.HttpClientFactory = new X509HttpFactory(GetCert()));

      fc1.WithHeader("User-Agent", userAgent)
         .WithHeader("Accept-Language", locale);

      dynamic ret1 = fc1.Url.AppendPathSegments(pathSegments).GetJsonAsync()
         .GetAwaiter().GetResult();
   }
   catch
   {
      // --> Exception: 403 FORBIDDEN
   }


   /****** NOT WORKING *******/
   try
   {
      IFlurlClient fc2 = new FlurlClient(url);

      fc2.Settings.HttpClientFactory = new X509HttpFactory(GetCert());

      fc2.WithHeader("User-Agent", userAgent)
         .WithHeader("Accept-Language", locale);

      dynamic ret2 = fc2.Url.AppendPathSegments(pathSegments).GetJsonAsync()
         .GetAwaiter().GetResult();
   }
   catch …
Run Code Online (Sandbox Code Playgroud)

c# client-certificates x509certificate2 .net-core flurl

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

从Flurl.Http v2.0.1中的请求取回cookie

使用Flurl.Http v1.2时,我们具有以下代码:

1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var client = url.EnableCookies();
4. ((HttpClientHandler)client.HttpMessageHandler).CookieContainer = cookieJar;
5. var result = await client.PostJsonAsync(new { UserName = userName, Password = password });
6. var cookies = cookieJar.GetCookies(new Uri(baseUrl));
7. _cookie = cookies[0];
Run Code Online (Sandbox Code Playgroud)

根据发行说明,升级到v2.0.1后,第4行不再编译,因为client不再是IFlurlClient它,而是现在的IFlurlRequest

我注意到它IFlurlRequest具有一个Client属性,因此我将第4行更改为:

4. ((HttpClientHandler)client.Client.HttpMessageHandler).CookieContainer = cookieJar;
Run Code Online (Sandbox Code Playgroud)

现在可以编译,但在运行时失败,并显示InvalidOperationException:

此实例已启动一个或多个请求。属性只能在发送第一个请求之前进行修改。

我假设这是由于底层HttpClient的主动重用。我在3到4之间添加了一行,以每次创建一个新的FlurlClient来确保实例无法启动请求。

1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var request = …
Run Code Online (Sandbox Code Playgroud)

c# flurl

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

Flul 数组编码

我试图将一些包含字符串数组的数据发布到端点,但收到错误“无效数组”

这样做:

   .PostUrlEncodedAsync(new
     {
        amount = 1000,
        allowed_source_types = new[] { "card_present" },
        capture_method = "manual",
        currency = "usd"
     });
Run Code Online (Sandbox Code Playgroud)

结果被发布:

金额=1000& allowed_source_types=card_present &capture_method=manual¤cy=usd

API 供应商抱怨我发布的数组无效。当我这样做时:

    .PostUrlEncodedAsync(
             "amount=1000&allowed_source_types[]=card_present&capture_method=manual&currency=usd"
    );
Run Code Online (Sandbox Code Playgroud)

结果被发布:

金额=1000& allowed_source_types[]=card_present &capture_method=manual¤cy=usd

API 供应商很高兴,我得到了预期的结果。

问题:这是一个错误吗? allowed_source_types 参数是否应该包含[ ](如最初详细说明的那样)

c# flurl

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

如何处理 flurl 中的错误请求异常

我是 Flurl 的新手。我正在尝试调用 api,我故意在参数中传递了无效的 apikey,然后 api 失败,说“禁止”并显示错误代码 403。我如何在异常中处理它?

 public async Task<myResponse> MyService(myRequest request)
    {
        try
        {


            return await new Flurl.Url("https://myapi.com/rest/age?apikey=XXXXXXXX").PostJsonAsync(apirequest).ReceiveJson<myResponse>();
        }
        catch (FlurlHttpException ex)
        {
            var statusCode = await ex.GetResponseJsonAsync<myResponse>();
            return await ex.GetResponseJsonAsync<myResponse>();

        }
Run Code Online (Sandbox Code Playgroud)

如果我得到状态代码 403,我想抛出我自己的自定义异常,但目前它在线失败var statusCode = await ex.GetResponseJsonAsync<myResponse>(); }

c# controller visual-studio flurl

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

如何阻止出站 HTTP 连接超时

背景:

我目前在 Azure 中托管一个具有以下规格的 ASP.NET 应用程序:

  • ASP .Net 核心 2.2
  • 使用 Flul 进行 HTTP 请求
  • Kestrel 网络服务器
  • Docker(Linux - mcr.microsoft.com/dotnet/core/aspnet:2.2 运行时)
  • P2V2 层应用服务计划上的 Azure 应用服务

我有几个在服务上运行的后台作业,这些作业对第三方服务进行大量出站 HTTP 调用。

问题:

在小负载(大约每 10 秒 1 次调用)下,所有请求都在一秒钟内完成,没有任何问题。我遇到的问题是,在重负载下,当服务可以在 10 秒内进行多达 3/4 次调用时,某些请求将随机超时并引发异常。当我使用 RestSharp 时,异常会显示“操作已超时”。现在我正在使用 Flurl,异常显示为“调用超时”。

关键在于 - 如果我从运行 Windows 10 / Visual Studios 2017 的笔记本电脑运行相同的作业,则不会出现此问题。这让我相信我在托管环境中遇到了某些限制或耗尽了某些资源。不清楚这是否与连接/套接字或线程相关。

我尝试过的事情:

  • 确保请求的所有代码路径都用于async/await防止锁定
  • 确保 Kestrel 默认允许无限连接(默认情况下)
  • 确保 Docker 默认连接限制足够(默认 2000 个,绰绰有余)
  • 配置ServicePointManager连接限制设置

这是我的startup.cs中的代码,我目前正在使用它来尝试防止此问题:

public class Startup
{
    public Startup(IHostingEnvironment hostingEnvironment)
    {
        ...

        // ServicePointManager setup
        ServicePointManager.UseNagleAlgorithm …
Run Code Online (Sandbox Code Playgroud)

azure kestrel docker flurl asp.net-core

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

HTTP 请求适用于 Postman,但不适用于 C# 代码

我想用 C# 做一个简单的 HTTP 请求,但有些东西不起作用,我得到的只是403 Forbidden状态代码。

当我尝试在 Postman 中执行相同的请求时,一切正常。我尝试运行 Fiddler 并查看 Postman 发送的所有标头。我复制粘贴了所有这些,但我仍然收到403 Forbidden了 C# 代码发送的请求。

C# 代码(使用https://fluurl.dev):

public static void Main(string[] args)
{
    FlurlHttp.Configure(settings => {
        settings.HttpClientFactory = new MyClientFactory();
    });

    var url = "https://example.com"
        .AppendPathSegments(new[] { "v1", "oauth", "accesstoken" })
        .SetQueryParam("grant_type", "client_credentials")
        .AllowAnyHttpStatus()
        .WithBasicAuth("username", "password")
        .WithHeaders(new {
            User_Agent = "Something/0.4.0 Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G975F Build/NRD90M)",
            X_Secret_Header = "secret_encoded_value",
            accept_encoding = "gzip, deflate",
            Accept = "*/*"
        });

    HttpResponseMessage msg = url.GetAsync().Result; …
Run Code Online (Sandbox Code Playgroud)

c# http request postman flurl

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