标签: dotnet-httpclient

从依赖注入配置进行依赖调用

我的需要是注入 HttpClient 并立即可供使用。但需要注意的是 HttpClient 需要设置Authorization标头,为此我需要再进行一次调用以获取令牌。我设法在启动的 RegisterServices 中完成所有这些配置,但我怀疑这是否是一个好主意。

services.AddHttpClient("OidcClient", (isp, client) =>
{
    var options = isp.GetRequiredService<IOptions<MyConfig>>().Value;
    client.BaseAddress = new Uri(options.OidcUrl);
});

services.AddHttpClient("MyClient", (isp, client) =>
{
    var options = isp.GetRequiredService<IOptions<MyConfig>>().Value;
    var oidcClient = isp.GetRequiredService<IHttpClientFactory>().CreateClient("OidcClient");
    var data = new Dictionary<string, string>
    {
        {"client_id", options.ClientId},
        {"client_secret", options.ClientSecret}
    };

    var request = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(data) };
    var response = oidcClient.SendAsync(request).Result;

    var token = response.Content.ReadFromJsonAsync<TokenResponse>().Result;

    client.BaseAddress = new Uri(options.Url);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
});
Run Code Online (Sandbox Code Playgroud)

然后它被正确地注入到我的代码中,我可以使用带有授权标头的客户端。

所以,我的担忧是: …

c# dependency-injection dotnet-httpclient .net-core .net-5

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

如何在.NET中使用HttpClient而不是WebClient下载Excel文件?

我有以下代码

private void SaveFile(string linkToFile, string filename)
{
    using WebClient client = new();
    client.DownloadFile(linkToFile, ResourcePath + filename);
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何使用 HttpClient 而不是 WebClient 下载 Excel 文件?

c# webclient dotnet-httpclient

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

找不到类型或命名空间名称“MediaTypeHeaderValue”

我使用创建了一个 C# 项目

cd /tmp
dotnet new console -o mydotnetapp
cd mydotnetapp
Run Code Online (Sandbox Code Playgroud)

然后我将 Program.cs 中的代码替换为发送带有自定义 Content-Type 标头的 Web 请求的代码:

cd /tmp
dotnet new console -o mydotnetapp
cd mydotnetapp
Run Code Online (Sandbox Code Playgroud)

我使用它运行它dotnet run并收到此错误:

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8888/");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("18233982904");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?这似乎是我使用旧版本的 HTTP 库时遇到的问题,但我的 .csproj 文件显示我正在使用 .NET 6

/private/tmp/mydotnetapp/Program.cs(8,43): error CS0246: The type or namespace name 'MediaTypeHeaderValue' …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient

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

使用 Polly 揭秘 HTTP 超时并重试

注册服务:

var host = new HostBuilder().ConfigureServices(services =>
{
    services.AddHttpClient<Downloader>(client =>
    {
        client.Timeout = TimeSpan.FromSeconds(1); // -- T1
    })
    .AddPolicyHandler(HttpPolicyExtensions
        .HandleTransientHttpError()
        .Or<HttpRequestException>()
        .WaitAndRetryAsync(Backoff.DecorrelatedJitterBackoffV2(
            TimeSpan.FromSeconds(5), // -- T2
            retryCount: 3)))
    .AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(10)) // -- T3
    .AddPolicyHandler(HttpPolicyExtensions
        .HandleTransientHttpError()
        .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30))); // -- T4

    services.AddTransient<Downloader>();

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

实施Downloader

class Downloader
{
    private HttpClient _client;
    public Downloader(IHttpClientFactory factory)
    {
        _client = factory.CreateClient();
    }

    public void Download(List<Uri> links)
    {
        await Parallel.ForEachAsync(
            links, 
            async (link, _cancelationToken) =>
            {
                await _client.GetStreamAsync(uri, _cancellationToken);
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

在此伪代码中,我对超时之间的相关性以及如何/何时重新提交 HTTP 请求感到困惑。具体来说: …

c# timeout dotnet-httpclient .net-core polly

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

不知何故,微软正在使用 SocketsHttpHandler 的受保护方法,但我不能

我正在尝试创建派生类,就像这里HttpMessageHandler所做的那样。我一开始就绊倒了,到目前为止我的代码:

public class InternetClientHandler : HttpMessageHandler
    {
        private readonly SocketsHttpHandler _socketsHttpHandler;

        public InternetClientHandler()
        {
            _socketsHttpHandler = new SocketsHttpHandler();
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return _socketsHttpHandler.SendAsync(request, cancellationToken); //ERROR
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是 Microsoft 实现的精确副本,HttpClientHandler但由于受保护,该方法无法编译_socketsHttpHandler.SendAsync。为什么它在 MS 的代码中有效,但在我的代码中无效?它是某种扩展方法吗?如果是这样,那么为什么 Intelli Sense 不提供帮助来插入正确的使用呢?SendAsyncSocketsHttpHandler

.net c# dotnet-httpclient

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

为什么在使用WebClient调用另一个控制器时返回500错误?

我正在测试此链接上的示例:http://msdn.microsoft.com/en-us/vs11trainingcourse_aspnetmvc4_topic5#_Toc319061802但我有500错误使用WebClient调用另一个控制器.

当我访问"http:// localhost:2323/photo/gallery直接运行,但我正在尝试使用WebClient进行操作时它返回500错误?为什么?"

   public ActionResult Index()
    {
        WebClient client = new WebClient();
        var response = client.DownloadString(Url.Action("gallery", "photo", null, Request.Url.Scheme));


        var jss = new JavaScriptSerializer();
        var result = jss.Deserialize<List<Photo>>(response);

        return View(result);
    }
Run Code Online (Sandbox Code Playgroud)

由以下异常创建的500错误:

[ArgumentNullException: Value cannot be null.
Parameter name: input]
   System.Text.RegularExpressions.Regex.Match(String input) +6411438
   Microsoft.VisualStudio.Web.Runtime.Tracing.UserAgentUtilities.GetEurekaVersion(String userAgent) +79
   Microsoft.VisualStudio.Web.Runtime.Tracing.UserAgentUtilities.IsRequestFromEureka(String userAgent) +36
   Microsoft.VisualStudio.Web.Runtime.Tracing.SelectionMappingExecutionListenerModule.OnBeginRequest(Object sender, EventArgs e) +181
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +69
Run Code Online (Sandbox Code Playgroud)

webclient asp.net-mvc-4 dotnet-httpclient

0
推荐指数
1
解决办法
2419
查看次数

具有基本身份验证的C#Windows应用商店HTTP HTTPClient导致401"未经授权"

我正在尝试向使用BASIC身份验证和https保护的服务发送HTTP GET请求.如果我使用RESTClient Firefox插件这样做没有问题.我正在定义basic-header并将GET发送到url,我得到了答案(json中的数据).

现在我正在使用C#中的Windows应用商店应用程序来使用该服务.我在清单中启用了所有必需的功能,并编写了以下方法:

private async void HttpRequest()
        {
            string basic = "Basic ...........";

            Uri testuri = new Uri(@"https://...Servlet");

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", basic);

            Task<HttpResponseMessage> response = client.GetAsync(testuri);
            var text = await response;
            var message = text.RequestMessage;
        }
Run Code Online (Sandbox Code Playgroud)

我尝试了许多不同的可能性,例如获取响应字符串但是所有内容都会导致服务器发出401状态代码答案.

我查看了许多类似的问题,我对通信的理解如下:客户端请求 - >服务器响应401 - >客户端发送授权标头 - >服务器响应200(确定)

我不明白为什么我得到401"未授权"状态代码,虽然我在开始时发送授权标题.如果有人知道如何在RESTClient中处理它,那将会很有趣.

BASIC标题是完全正确的我将它与RESTClient中的标题进行比较.

如果有人可以帮助我,这将是很好的.

在此先感谢您的亲切问候,Max

c# basic-authentication http-status-code-401 dotnet-httpclient

0
推荐指数
1
解决办法
2733
查看次数

如何在vb.net中使用HttpClient读取JSON响应

我已经构建了一个用于访问WEB API服务的java例程,但是我正在为ASP.Net的VB等价物而苦苦挣扎.我得到API响应,但我不知道如何将其转换为json元素.

java版本是:

    public boolean canLogin(){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(hostURL + TOKEN_ACCESS_URL);
    httppost.addHeader("Accept", "application/json");

    // Add the post content
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
    nameValuePairs.add(new BasicNameValuePair("username", accessUserName));
    nameValuePairs.add(new BasicNameValuePair("password", accessPassword));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        mobileLogDataHandler.ToLog(LogType.Error, "UnsupportedEncodingException closing data stream with error: " + e1.getLocalizedMessage() + ",detail:" + e1.getMessage() + " in canLogin", mResolver, RemoteDataHandler.class);
        return false;
    }

    // post the server
    InputStream inputStream = null;
    String …
Run Code Online (Sandbox Code Playgroud)

vb.net asp.net-web-api dotnet-httpclient

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

通过ipaddress访问网站

我试图通过IP地址而不是http地址访问网站.我正在尝试一些众所周知的网站,如微软和谷歌,并通过ping他们获取他们的IP地址.例如184.87.106.199是微软,216.58.221.68是谷歌.

    async Task<HttpStatusCode> RequestPage(string url, HttpClient client) {
        var request = new HttpRequestMessage();

        try {
            var response = await client.GetAsync("http://" + url);

            Console.WriteLine(string.Format("{0} - {1}", url, response.StatusCode.ToString()));

            return response.StatusCode;
        } catch (TaskCanceledException) {
            Console.WriteLine(string.Format("{0} - Timeout", url));

            return HttpStatusCode.GatewayTimeout;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是它似乎并不适用于每个站点.如果我请求http://216.58.221.68谷歌工作正常,但微软返回一个错误的请求状态.

我错过了什么?

c# dotnet-httpclient

0
推荐指数
1
解决办法
40
查看次数

C#中的异步Main并阻止异步Http调用

我对我认为纯粹是异步程序的输出感到困惑。如您所见,没有明显的反模式(希望如此)和阻止呼叫。

slowURL限制服务器响应10秒钟。我确实通过在10秒钟的超时时间内运行对本地服务器的调用来确认,FetchSlowAsync在控制台中运行代码时,该方法调用有效地阻塞了主线程10秒钟。

我希望TaskScheduler不会按顺序安排调用,而是总是随机确定方法的调用顺序。las,输出始终是确定性的。

FetchSlowAsync start
FetchSlowAsync got data!
FetchAsync start
FetchAsync got data!
FetchBingAsync start
FetchBingAsync got data!
All done!
Run Code Online (Sandbox Code Playgroud)

我的问题是:是什么促使FetchSlowAsync阻塞而不是TaskScheduler执行上下文切换到另一个异步方法,并在完成后返回到它?

下一个问题是前一个问题:async Main在异步执行模型是并发的情况下,为什么其中的所有方法都按照被调用的相同顺序执行?

FetchSlowAsync start
FetchSlowAsync got data!
FetchAsync start
FetchAsync got data!
FetchBingAsync start
FetchBingAsync got data!
All done!
Run Code Online (Sandbox Code Playgroud)

c# concurrency async-await dotnet-httpclient .net-core

0
推荐指数
1
解决办法
224
查看次数