logo
Tags down

shadow

HttpClient static with new


By : Lawrence Kemp
Date : September 15 2020, 04:00 AM
hope this fix your issue I'm not entirely sure where you were reading that pointed you towards your current implementation, especially since you are saying multiple sources gave you this idea.
My assumption is that you misread these sources as showing you a normal consturctor, instead of a static one?
code :
class ClientClass 
{
    private static readonly HttpClient client;
    static ClientClass() 
    {
        client = new HttpClient();
    }
}


Share : facebook icon twitter icon

Implement Static HttpClient in Web App


By : Armaan Sabharwal
Date : March 29 2020, 07:55 AM
I wish this helpful for you Your problem is due to async void. As noted in my intro to async on ASP.NET article:
code :
public static class SchedulerHttpClient
{
  ... // Same as above, but making MainAsync private.
  public static readonly Lazy<Task> Initialize = new Lazy<Task>(() => MainAsync());
}
public async Task<ActionResult> Index()
{
  await SchedulerHttpClient.Initialize.Value.ConfigureAwait(false);
  try
  {
    await MakeARMRequests().ConfigureAwait(false);
  }
  catch (Exception e)
  {
    Console.WriteLine(e.GetBaseException().Message);
  }

  return View();
}
public static class SchedulerHttpClient
{
  private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
  {
    var client = new HttpClient();
    await MainAsync(client).ConfigureAwait(false);
    return client;
  });
  public static Task<HttpClient> ClientTask => _Client.Value;

  private static async Task MainAsync(HttpClient client) { ... }
  private static async Task<string> AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret) { ... }
  private static async Task<dynamic> HttpPost(HttpClient client, string tenantId, string payload) { ... }
}

Canceling an async call on a static HttpClient


By : carlos_godfather
Date : March 29 2020, 07:55 AM
Hope this helps Each SendAsync call is totally independent from each other, canceling the token for one request does not cancel other outstanding requests.
Your assumption that because HttpClientHandler is shared for all requests that means all requests get canceled is incorrect. If you look in to the decompiled source of HttpClientHandler you will see
code :
[__DynamicallyInvokable]
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
  if (request == null)
    throw new ArgumentNullException(nameof (request), SR.net_http_handler_norequest);
  this.CheckDisposed();
  if (Logging.On)
    Logging.Enter(Logging.Http, (object) this, nameof (SendAsync), (object) request);
  this.SetOperationStarted();
  TaskCompletionSource<HttpResponseMessage> completionSource = new TaskCompletionSource<HttpResponseMessage>();
  HttpClientHandler.RequestState state = new HttpClientHandler.RequestState();
  state.tcs = completionSource;
  state.cancellationToken = cancellationToken;
  state.requestMessage = request;
  try
  {
    HttpWebRequest prepareWebRequest = this.CreateAndPrepareWebRequest(request);
    state.webRequest = prepareWebRequest;
    cancellationToken.Register(HttpClientHandler.onCancel, (object) prepareWebRequest);
    if (ExecutionContext.IsFlowSuppressed())
    {
      IWebProxy webProxy = (IWebProxy) null;
      if (this.useProxy)
        webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
      if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
        this.SafeCaptureIdenity(state);
    }
    Task.Factory.StartNew(this.startRequest, (object) state);
  }
  catch (Exception ex)
  {
    this.HandleAsyncException(state, ex);
  }
  if (Logging.On)
    Logging.Exit(Logging.Http, (object) this, nameof (SendAsync), (object) completionSource.Task);
  return completionSource.Task;
}

Refresh Token using Static HttpClient


By : S Duv
Date : March 29 2020, 07:55 AM
like below fixes the issue update: added the SemaphoreSlim to "lock" the refresh transaction
disclaimer: not tested, might need some tweaking
code :
public class MyHttpMessageHandler : HttpMessageHandler
{
    private static SemaphoreSlim sem = new SemaphoreSlim(1);

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {  
    var response = await base.SendAsync(request, cancellationToken);

    //test for 403 and actual bearer token in initial request
    if (response.StatusCode == HttpStatusCode.Unauthorized &&
        request.Headers.Where(c => c.Key == "Authorization")
                .Select(c => c.Value)
                .Any(c => c.Any(p => p.StartsWith("Bearer"))))
        {

            //going to request refresh token: enter or start wait
            await sem.WaitAsync();

            //some typical stuff
            var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                new KeyValuePair<string, string>("refresh_token", yourRefreshToken),
                new KeyValuePair<string, string>("client_id", yourApplicationId),
            };

            //retry do to token request
            using ( var refreshResponse = await base.SendAsync(
                new HttpRequestMessage(HttpMethod.Post, 
                   new Uri(new Uri(Host), "Token")) 
                   { 
                      Content = new FormUrlEncodedContent(pairs) 
                   }, cancellationToken))
            {
                var rawResponse = await refreshResponse.Content.ReadAsStringAsync();
                var x = JsonConvert.DeserializeObject<RefreshToken>(rawResponse);

                //new tokens here!
                //x.access_token;
                //x.refresh_token;

                //to be sure
                request.Headers.Remove("Authorization");
                request.Headers.Add("Authorization", "Bearer " + x.access_token);

                //headers are set, so release:
                sem.Release();  

                //retry actual request with new tokens
                response = await base.SendAsync(request, cancellationToken);

            }
        }

        return response;
    }
}
}
public async Task<int> RegisterAsync(Model model)
{
    var response = await YourHttpClient
       .SendAsync(new HttpRequestMessage(HttpMethod.Post, new Uri(BaseUri, "api/Foo/Faa"))
    {  
        Content = new StringContent(
           JsonConvert.SerializeObject(model),
           Encoding.UTF8, "application/json")
    });

    var result = await response.Content.ReadAsStringAsync();
    return 0;
}

Static HttpClient still creating TIME_WAIT tcp ports


By : Lyon Liu
Date : March 29 2020, 07:55 AM
I hope this helps you . Short version
Use .NET Core 2.1 if you want to reuse connections with NTLM authentication
code :
HttpClient _client;

public void InitTheClient()
{
    var handler=new WebRequestHandler
                { 
                    UseDefaultCredentials=true,
                    UnsafeAuthenticatedConnectionSharing =true
                };
    _client=new HttpClient(handler); 
}

HttpClient initialization within a static class


By : IFulea
Date : March 29 2020, 07:55 AM
I wish this helpful for you I'm learning C#. Would it be correct to initilize an HttpClient within a static class like this? , Yes you can achieve that by doing this:
code :
static readonly HttpClient httpClient = new HttpClient
{
    BaseAddress = new Uri(Network.baseAddress),
    DefaultRequestHeaders =
    {
        Authorization =
            new AuthenticationHeaderValue("Bearer", Network.token)
    }
};
Related Posts Related Posts :
  • Why is my commit button not going through its for loop?
  • How can I declare a variable with name 'operator'?
  • Deadlock when calling an async method inside a non async action
  • Visual Studio 2019 closing curly brace not under the opening brace (it's fully left aligned instead)
  • How to access and change the property of a label that I created dynamically
  • Calling a method that returns a random number from inside a loop
  • How to import binary heaps in C#
  • C# Driver MongoDb: How to use "UpdateOneAsync"
  • How to use the data from reading a file
  • How to define local variable in a select LINQ-query
  • Using CultureInfo in order to replace USD symbol with -
  • Is it too early to migrate from .net core 2.2 to .net core 3?
  • Accessing null value leads to application fail / C#
  • Mask first 3 Characters in the Email with "*"
  • Stop method from execution
  • Keep one number after decimal point, not rounding
  • Read a Siemens PLC s7 String in C# with S7netplus
  • How to call a stored procedure in EF Core 3.0 via FromSqlRaw
  • Best workaround for not being able to inherit a sealed class?
  • How do you reference a variable from another class?
  • How to instantiate a class as the interface that it derives from with constrained generic type parameter
  • Is it possible to do a .NET Core DLL containing .NET Core Framework?
  • C# writing JSON to a file without backslashes
  • How to remove special characters from input text box and display in a label?
  • How to make the first or last letter of every word in a string lowercase
  • Transfer variables between scenes
  • Cross apply two list, return same modified object
  • How to stop propagating an asynchronous stream (IAsyncEnumerable)
  • Fatal Error: Public Main() method is required in a public class
  • C# calorie counter
  • How can i make a proper if/else if/else statement?
  • How to force an IAsyncEnumerable to respect a CancellationToken
  • "the term 'add-migration' is not recognized as the name of a cmdlet" visual studio 2019
  • How to deal with optional data in a typed domain model?
  • Reasons to not throw when implementing `IComparable<T>`?
  • How to properly instantiate dynamically derived objects and their members in C#
  • How to assert in selenium webdriver in C#?
  • How to display version number a certain way
  • What is the main PURPOSE of Composition in C#?
  • DropDown List is empty when generating a view from the model
  • Simple question about the name of an expression containing ? :
  • How to fix 'DataTable' does not contain a definition for 'AsEnumerable' Error in Microsoft Botframework v4?
  • Wrong Date value if day or month properties are one digit
  • Is there a way i can draw a transparent WPF application over the desktop at all times?
  • Issue With Foreign Key in mvc?
  • Cannot add custom user data to scaffolded ASP.NET Core project
  • Microsoft DI Container _transientDisposables not disposed (memory leak)
  • Is there any shortcut to add the lambda/func arrow operator => in Visual Stuido 2019?
  • Client certificate with HttpClient in c#
  • Complex IEnumerable Result from LINQ Select
  • Performance Way to check if a byte array contains another byte Array C#
  • Repository pattern and change log implementation
  • DotNet core 3.0 compilation issues in VSCode
  • How to create a random spawner in unity 2d?
  • MVC API not hitting controller
  • Getting data from SQL Server with C#
  • How to compare two arrays of chars and see location?
  • Asynchronous code, shared variables, thread-pool threads and thread safety
  • Upgrading HTK GazeManager to MRTK v2 Pointer (HandRay...)
  • How to split an overridden method into multiple files?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk