标签: dotnet-httpclient

使用 C# HTTPClient 发布 HTTP 请求

我正在尝试发布登录网页的请求。

原始 POST 请求

原始 POST 请求第 2 部分

我以前没有做过 POST 请求。我正在使用以下代码进行测试。我正在尝试弄清楚请求的正文。

public async void PostRequest()
{
    using (var client = new HttpClient())
    {
        var values = new Dictionary<string, string>
        {
            { "loginForm", "loginForm" },
            { "userName385076574", "005847951" },
            { "password908645299", "Password" },
            { "javax.faces.ViewState", "e1s1"},
            { "as_sfid", "?" },
            { "as_fid", "?"},
            { "j_idt26", "?" }
        };

        var content = new FormUrlEncodedContent(values);
        client.DefaultRequestHeaders.Add("User-Agent", "C# App");
        //  client.
        var response = await client.PostAsync("https://gkmpay.oberthur.com/mui/mwallet/webTerminal?execution=e1s2", content);

        var responseString = await response.Content.ReadAsStringAsync();
    } …
Run Code Online (Sandbox Code Playgroud)

c# post dotnet-httpclient

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

如何从 webApi 上的 http 请求中检索 CancellationToken?

我通过 HttpClient 向服务器发送请求:

public async Task GetTest()
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    string url = String.Format($"api/Test/getTest");

    HttpResponseMessage response = await _httpClientFactory.HttpClient.GetAsync(url, tokenSource.Token).ConfigureAwait(false);

    response.EnsureSuccessStatusCode();
}
Run Code Online (Sandbox Code Playgroud)

在WebApi(Core 2.1)上方法是这样的:

[HttpGet("getTest")]
public async Task<IActionResult> GetTest(CancellationToken token)
{
    try
    {
        object test = await _dataService.GetTest(token);

        return Ok(test);
    }
    catch (Exception ex)
    {
        this._logger.LogError(ExceptionHelper.ExMessageDeepGet(ex));
        return new InternalServerErrorWithMessageResult(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

_dataService.GetTest(token)我做token.ThrowIfCancellationRequested();

问题是我在 webapi 上获得了新令牌,而不是通过客户端发送的令牌,因此如果我在 api 响应之前停止请求(关闭客户端),则不会引发异常。

有什么建议么?

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

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

如何在 .NET Core 控制台应用程序中启用 HttpClient 的日志记录?

.NET 核心 2.2

我有一个使用创建的基本 CLI dotnet new console。它用于HttpClient发出网络请求。如何查看有关这些请求的跟踪或日志记录信息?

像这样的数据: https: //www.stevejgordon.co.uk/httpclientfactory-asp-net-core-logging

在 .NET Framework 中,您可以打开系统跟踪:https://learn.microsoft.com/dotnet/framework/network-programming/how-to-configure-network-tracing

console-application dotnet-httpclient .net-core

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

如何修复“AADSTS90102:‘redirect_uri’值必须是有效的绝对 Uri。” Microsoft Graph 中的错误

按照此过程操作: https://learn.microsoft.com/en-us/graph/auth-v2-user

我正在尝试从此 Microsoft 端点获取刷新令牌: https://login.microsoftonline.com/ {tenantId}/oauth2/v2.0/authorize

使用nuget (asp.net core 2.2) 库中System.Net.Http.HttpClient类的 PostAsync 方法,我能够收到以下错误的响应:“AADSTS90102:'redirect_uri'值必须是有效的绝对 Uri。 ” : https://i.imgur.com/LhP5kYf.png

我尝试在 Azure 门户中设置一些重定向 url,包括: https://automation.legroupeti.com/Configurations/GetRefreshToken/ https://automation.legroupeti.com/Configurations/GetRefreshToken https://automation.legroupeti.com/ https://automation.legroupeti.com

post 请求如下(使用nuget (asp.net core 2.2) 中System.Net.Http.HttpClient类的 PostAsync 方法): https://i.imgur.com/PI4mo8Y.png

以下是在 Azure 门户中注册的应用程序配置的重定向 URL: https://i.imgur.com/aqYDJhn.png

我期望来自端点的有效响应。如何配置redirect_uri才有效?

编辑1

我修复了redirect_uri参数。

dotnet-httpclient azure-active-directory asp.net-core refresh-token microsoft-graph-api

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

Upload progress using HttpClient in Blazor Wasm

I'm trying to get file upload progress inside a blazor web assembly app.

var handler = new ProgressMessageHandler();
handler.InnerHandler = new WebAssemblyHttpMessageHandler();
handler.HttpSendProgress += (object sender, HttpProgressEventArgs e) =>
{
    Console.WriteLine("bytes transfered= " + e.BytesTransferred.ToString());
    Console.WriteLine("total bytes= " + e.TotalBytes.ToString());
    Console.WriteLine("progress percentage= " + e.ProgressPercentage.ToString());
};

var http = new HttpClient(handler);
http.BaseAddress = new Uri(NavigationManager.BaseUri);
await http.PostJsonAsync("api/...", attachedFile);

Console.WriteLine("Done");
Run Code Online (Sandbox Code Playgroud)

I came up with the following code, but when I upload a file I get a single event instantly reporting 100% …

.net c# dotnet-httpclient blazor blazor-client-side

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

使用 Polly 断路器处理多项服务的正确方法

我有一个应用程序,我们可以在其中与数百个 HTTP 端点进行通信。该应用程序是某种代理。

在使用 polly 进行测试时,我注意到如果一个端点(比如api.endpoint1.com失败),对api.endpoint2.com和 的调用api.endpoint3.com也将处于打开/阻止状态。

这是有道理的,因为我只定义了一个策略,但是处理这种情况的推荐方法是什么,以便对不相关端点的调用不会因另一个端点出现性能问题而被阻止?

我是否创建一组策略,每个端点一个,或者是否有一种方法提供某种上下文键(即主机名)来将故障范围限制到给定的主机端点?

我已经查看了Polly 的有关上下文键的文档,看来这些是一种来回交换数据的方法,而不是我在这里寻找的。

var policy = Policy
            .Handle<TimeoutException>()
            .CircuitBreaker(1, TimeSpan.FromSeconds(1));
                
//dynamic, large list of endpoints. 
var m = new HttpRequestMessage(HttpMethod.Post, "https://api.endpoint1.com")
{
    Content = new StringContent("some JSON data here", Encoding.UTF8,"application/json")
};


policy.Execute(() => HTTPClientWrapper.PostAsync(message));
Run Code Online (Sandbox Code Playgroud)

.net c# circuit-breaker dotnet-httpclient polly

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

对多个端点使用 HttpClient 和 HttpClientHandler 的最佳实践是什么?

使用HttpClient并不像我希望的那么简单。尽管它是一种IDisposable类型,但将其包装在声明中并不是最佳实践using,甚至将其设置为单例也是理想的选择。HttpClientHandler但是,当您将 a 传递给类似的构造函数时会怎么样HttpClient

using (var client = new HttpClient(singletonHttpClientHandler, false);
Run Code Online (Sandbox Code Playgroud)

我见过像上面这样的代码,其中HttpClient故意将 包裹在using语句中,但HttpClientHandler是单例。文档表明客户端处理程序已被处理,除非第二个参数指示false如上面所做的那样:

在此输入图像描述

请参阅https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#constructors

使用 HttpClient 的部分问题是一些事情,比如超时必须与该 HttpClient 的所有实例共享,因此出于这个原因,最好创建使用 HttpClientHandler 提供的相同连接池的单独的 HttpClient 实例(假设这就是它的工作原理)。我担心的是,我不希望 HttpClient 创建一个连接池,然后每次都会将其释放。有很多帖子讨论了这对性能有何影响。我似乎找不到任何关于有效使用 HttpClient 和 HttpClientHandlers 的好的文档。

所以...我的问题基本上是:

当一起使用 HttpClient 和 HttpClientHandler 时,是否最好将 HttpClientHandler 设为单例,然后using每次在块中实例化尽可能多的新 HttpClient?-- 这又只有当连接池由 HttpClientHandler 管理时才有意义,我认为就是这种情况。

c# dotnet-httpclient httpclienthandler

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

如何在 HttpClient 的帮助下仅使用键值参数发送表单数据 POST 请求

如何在 HttpClient 的帮助下仅使用键值参数发送表单数据 POST请求?

这是我的方法的代码:

public async Task<HttpResponseMessage> MakePostAsync(string endpoint, string token, Dictionary<string, string> headers = null, KeyValuePair<string, string>[] parameters = null)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers.Add(header.Key, header.Value);
            }
            request.Headers.Add("Content-Type", "multipart/form-data");
            var formaData = new MultipartFormDataContent();

            formaData.Add(new StringContent(token), "__RequestVerificationToken");
            formaData.Add(new StringContent("admin"), "Username");
            formaData.Add(new StringContent("1"), "Password");
            request.Content = formaData;


            HttpResponseMessage response = await Task.Run(() => client.SendAsync(request));
            return response;
        }
Run Code Online (Sandbox Code Playgroud)

JavaScript 上的 Postan 中的相同请求,但它有效

c# multipartform-data request dotnet-httpclient

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

Polly 使用不同的 url 重试

我正在尝试使用 polly 创建一个解决方案,其中我请求其他 api。
我有同一服务的多个实例的 URL 列表。
我希望当第一个请求失败时,另一个请求应该自动从我的列表中的下一个网址开始。

这是一个示例,我使用两个静态地址尝试此行为。
此解决方案的问题是,在我开始下一个请求之前,url 不会更改。我希望每次重试时网址都会改变

 public static void ConfigureUserServiceClient(this IServiceCollection services)
    {

        _userServiceUri = new Uri("https://localhost:5001");

        services.AddHttpClient("someService", client =>
        {
            client.BaseAddress = _userServiceUri;
            client.DefaultRequestHeaders.Add("Accept", "application/json");
        }).AddPolicyHandler(retryPolicy());
    }

    private static IAsyncPolicy<HttpResponseMessage> retryPolicy()
    {
        return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.RequestTimeout)
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt),
            onRetry: (result, span, ctx) =>
            {
                _userServiceUri = new Uri("https://localhost:5002");
            });
    }
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient polly asp.net-core retry-logic

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

如何修复 HttpClient 中的 SSL 身份验证问题:Azure Linux 应用服务

我很难找到解决此问题的方法,因为它只发生在 Azure Linux 应用服务中。在本地(win10)和Azure Windows应用程序服务中,没有问题。

该应用程序是 ASP.NET Core 3.1,我创建了一个自定义服务作为 HttpClient:

        private readonly HttpClient _client;

        public NPIApiService(HttpClient client)
        {
            _client = client;
            _client.BaseAddress = new Uri("https://npiregistry.cms.hhs.gov/api/");
        }

        public class AllowCertsMessageHandler : HttpClientHandler
        {
            public AllowCertsMessageHandler()
            {
                this.ClientCertificateOptions = ClientCertificateOption.Manual;
                this.ServerCertificateCustomValidationCallback = (requestMessage, cert, certChain, policyErrors) =>
                {
                    return true;
                };
            }
        }

        public async Task<NPIResult> LoadNPI(string npi)
        {
            var response = await _client.GetAsync(new Uri($"?version=2.1&number={npi}", UriKind.Relative), HttpCompletionOption.ResponseContentRead);
            if (response.IsSuccessStatusCode)
            {
                var rawstring = await response.Content.ReadAsStringAsync();
                return System.Text.Json.JsonSerializer.Deserialize<NPIResult>(rawstring);
            }

            return null;
        }
Run Code Online (Sandbox Code Playgroud)

请注意 …

openssl dotnet-httpclient azure-web-app-service azure-linux asp.net-core-3.1

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