解决  DeleteAsyn不起作用

madaxe2020

会员
已加入
2020年9月7日
留言内容
17
编程经验
5-10
我无法让DeleteAsync工作,它在DeleteAsyn控制器在期待下面的Json主体的过程中,在高亮显示的第20行默默地失败了

有人可以帮忙吗?

谢谢

马达克斯

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

会员
已加入
2020年9月7日
留言内容
17
编程经验
5-10
我修复了我的代码,但是如果每次都失败,则无法强烈键入“ HttpResponseMessage”。

为什么?

谢谢

马达克斯


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;
        }
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,499
地点
弗吉尼亚州切萨皮克
编程经验
10+
我修复了我的代码,但是如果每次都失败,则无法强烈键入“ HttpResponseMessage”。

为什么?
失败时会遇到什么错误?
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,499
地点
弗吉尼亚州切萨皮克
编程经验
10+
As an aside, this code is improper use of HttpClient():
C#:
using (HttpClient httpClient = new HttpClient())

看到:
 

madaxe2020

会员
已加入
2020年9月7日
留言内容
17
编程经验
5-10
As an aside, this code is improper use of HttpClient():
C#:
using (HttpClient httpClient = new HttpClient())

看到:
很棒的文章,谢谢

现在,我已经将HTTPClient移到了Static,它完全破坏了代码,它进入 PostAsyn 立即以空值跳转到函数末尾的Return

有什么想法吗

马达克斯

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;
        }
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,499
地点
弗吉尼亚州切萨皮克
编程经验
10+
它不能不抛出异常就跳到方法的末尾。在第33行上设置一个断点以查看异常是什么。
 

madaxe2020

会员
已加入
2020年9月7日
留言内容
17
编程经验
5-10
如果我使用 静态HttpClient 客户我得到一个 System.Net.HttpStatusCode.Forbidden 在HttpResponseMessage.StatusCode

如果我在方法中使用创建HttpClient的话,为什么可以正常工作?

谢谢

马达克斯



Static Class:
public static class ContinentDatabase
    {
        private 静态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

会员
已加入
2020年9月7日
留言内容
17
编程经验
5-10
因此,我将其范围缩小到许多请求标头,我最初的GetContinents具有两个请求标头,它们与add,update和delete方法相同,因此它们很复杂。

使用静态HTTPClient时添加和删除请求标头的最佳方法是什么

谢谢

马达克斯


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

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,499
地点
弗吉尼亚州切萨皮克
编程经验
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.
 
最佳 底部