Resolved DeleteAsyn Not Working

madaxe2020

Member
Joined
Sep 7, 2020
Messages
17
Programming Experience
5-10
I cant get my DeleteAsync working it silently fails at the highlited line 20 during the DeleteAsyn my controller is expecting the Json body below

Can anybody help?

Thanks

Madaxe

json Body:
{
        "continent_name": "Test"
}


Delete Async:
        public static bool DeleteContinentData(string ContinentName)
        {
            bool ReturnBoolean = false;
            Task<bool> ApplicationTask = ContinentDatabase.DeleteContinent(ContinentName);
            ApplicationTask.Wait();
            return ReturnBoolean;
        }

        private static async Task<bool> DeleteContinent(string ContinentName)
        {
            bool ReturnBoolean = false;
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
                    httpClient.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);


                    using (var content = new StringContent(JsonConvert.SerializeObject(new Dictionary<string, object>(){{ "continent_name", ContinentName } }), System.Text.Encoding.UTF8, "application/json"))
                    {
                        using (HttpResponseMessage HttpResponseMessage = await httpClient.DeleteAsync(ContinentDatabase._Url).ConfigureAwait(false))
                        {
                            if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return ReturnBoolean;
        }
 

madaxe2020

Member
Joined
Sep 7, 2020
Messages
17
Programming Experience
5-10
I fixed my code but i cant strongly type the 'HttpResponseMessage' if i do it fails everytime.

Why?

Thanks

Madaxe


Fixed Code:
        private static async Task<bool> DeleteContinent(string ContinentName)
        {
            bool ReturnBoolean = false;
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
                    httpClient.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);

                    using (HttpRequestMessage request = new HttpRequestMessage())
                    {
                        request.Method = HttpMethod.Delete;
                        request.Content= new StringContent(JsonConvert.SerializeObject(new Dictionary<string, object>() { { "continent_name", ContinentName } }), Encoding.UTF8, "application/json");
                        request.RequestUri = new Uri(ContinentDatabase._Url);
                        var HttpResponseMessage = await httpClient.SendAsync(request).ConfigureAwait(false);

                        if(HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            ReturnBoolean = true;
                        }
                    }   
      
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return ReturnBoolean;
        }
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,959
Location
Chesapeake, VA
Programming Experience
10+
I fixed my code but i cant strongly type the 'HttpResponseMessage' if i do it fails everytime.

Why?
What error are you getting when it fails?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,959
Location
Chesapeake, VA
Programming Experience
10+
As an aside, this code is improper use of HttpClient():
C#:
using (HttpClient httpClient = new HttpClient())

See:
 

madaxe2020

Member
Joined
Sep 7, 2020
Messages
17
Programming Experience
5-10
As an aside, this code is improper use of HttpClient():
C#:
using (HttpClient httpClient = new HttpClient())

See:
Great Article, thanks

Now I've moved the HTTPClient to a Static it completely broke the code, it gets to PostAsyn immediately jumps to the Return at the end of the function with a null value

any thoughts

Madaxe

Code Change:
public static Continent CreateContinentData(Continent NewContinent)
        {
            Continent ReturnContinent = null;
            Task<Continent> ApplicationTask = ContinentDatabase.CreateContinent(NewContinent);
            ApplicationTask.Wait();
            return ReturnContinent;
        }
        private static async Task<Continent> CreateContinent(Continent NewContinent)
        {
            Continent ReturnContinent = null;
            try
            {
                ContinentDatabase.Client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
                ContinentDatabase.Client.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);

                using (var content = new StringContent(JsonConvert.SerializeObject(NewContinent), System.Text.Encoding.UTF8, "application/json"))
                {
                    using (HttpResponseMessage HttpResponseMessage = await ContinentDatabase.Client.PostAsync(ContinentDatabase._Url, content).ConfigureAwait(false))
                    {
                        if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            using (HttpContent HttpContent = HttpResponseMessage.Content)
                            {
                                string MyContent = await HttpContent.ReadAsStringAsync();
                                ReturnContinent = (ContinentDatabase.DeserializeObject<Continent>(MyContent));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return ReturnContinent;
        }
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,959
Location
Chesapeake, VA
Programming Experience
10+
It can't just jump to the end of the method without throwing an exception. Set a breakpoint on line 33 to see what the exception is.
 

madaxe2020

Member
Joined
Sep 7, 2020
Messages
17
Programming Experience
5-10
If i use the static HttpClient Client i get a System.Net.HttpStatusCode.Forbidden at the HttpResponseMessage.StatusCode

if i use the create the HttpClient in the method it works fine why?

Thanks

Madaxe



Static Class:
public static class ContinentDatabase
    {
        private static HttpClient Client = new HttpClient();



Methods:
        public static Continent CreateContinentData(Continent NewContinent)
        {
            Continent ReturnContinent = null;
            Task<Continent> ApplicationTask = ContinentDatabase.CreateContinent(NewContinent);
            ApplicationTask.Wait();
            return ReturnContinent;
        }
        private static async Task<Continent> CreateContinent(Continent NewContinent)
        {
            Continent ReturnContinent = null;
            try
            {
                HttpClient Client = new HttpClient();
                Client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
                Client.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);

                //ContinentDatabase.Client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
                //ContinentDatabase.Client.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);

                using (HttpRequestMessage request = new HttpRequestMessage())
                {
                    request.Method = HttpMethod.Post;
                    request.Content = new StringContent(JsonConvert.SerializeObject(NewContinent), System.Text.Encoding.UTF8, "application/json");

                    request.RequestUri = new Uri(ContinentDatabase._Url);
                    var HttpResponseMessage = await ContinentDatabase.Client.SendAsync(request).ConfigureAwait(false);

                    if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        using (HttpContent HttpContent = HttpResponseMessage.Content)
                        {
                            string MyContent = await HttpContent.ReadAsStringAsync();
                            ReturnContinent = (ContinentDatabase.DeserializeObject<Continent>(MyContent));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return ReturnContinent;
        }
 

madaxe2020

Member
Joined
Sep 7, 2020
Messages
17
Programming Experience
5-10
So I've narrowed it down to to many request headers, my initial GetContinents had two request headers the same as the add, update and delete methods, so they were compounding.

What the best way to add and remove request headers when using a static HTTPClient

Thanks

Madaxe


ContinentDatabase.Client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8");
ContinentDatabase.Client.DefaultRequestHeaders.Add("x-api-key", ContinentDatabase._APIKey);
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
1,959
Location
Chesapeake, VA
Programming Experience
10+
If the headers are static, create multiple static HttpClient's. If you the headers are dynamic for each request, create a custom HttpClientHandler. In your handler's SendAsync implementation, insert the needed dynamic headers.
 
Top Bottom