Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jonathan Bäckström 6 posts 96 karma points
    Aug 10, 2018 @ 08:53
    Jonathan Bäckström
    0

    Create single instance of HttpClient

    Hi,

    I am using HttpClient to send GET and POST requests. According to this article you should not create a new instance of the HttpClient before each call but rather reuse one instance through out the lifetime of the application.

    So instead of:

    var client = new HttpClient()
    var response = client.GetAsync(url);
    

    I would like to use a global instance of client.

    How can you create such reusable instances in Umbraco?

    Where can I put the code so it is created at start and survives as long as the application is running?

    Thanks!

  • Bex 444 posts 555 karma points
    Oct 09, 2019 @ 12:50
    Bex
    0

    @Jonathan

    I know it's a long time since you posted this but do you remember what you ended up doing?

  • Chester Campbell 98 posts 209 karma points
    Oct 09, 2019 @ 22:30
    Chester Campbell
    0

    A simple solution would be to create a static class that holds a static instance of HttpClient. For example:

    namespace MyProjectCode
    {
        public static class EmailHelper
        {
            public static System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        }
    }
    

    Then to use it elsewhere in your code:

    HttpResponseMessage response = await MyProjectCode.EmailHelper.client.PostAsJsonAsync("https://urltosomething.com", Newtonsoft.Json.JsonConvert.SerializeObject(myObject));
    
Please Sign in or register to post replies

Write your reply to:

Draft