HTTP请求不会返回任何信息,也不会使用C.使用System.Net.Http返回错误;

问题描述 投票:0回答:1

我在Xamarin.Forms项目中有一个类负责处理Http请求,特别是Get和Post请求,该API位于azure中,当我通过在浏览器中插入URL进行调用时,它可以正常工作,并且它返回了应该返回的内容,对于Post 1也是如此。

问题是,当我从代码中执行调试时,调试将在到达以下要通知的行时结束。它不会给出结果,也不会给出错误。

在此之前,我在API和Xamarin Forms项目中都进行了一些更改。我在项目中所做的更改是在我用于get()和Post()的类中删除了一个参数,但是我也更改了API,因此它在Get请求中不提供该参数,并且不请求它在帖子中。

获取并设置代码:

class ApiDataBaseService : IApiDataBaseService
    {
        public async Task<string> GetData(string url) //Both URLs work fine as I said before
        {
            var client = new HttpClient 
            {
                BaseAddress = new Uri(url)
            };

            var response = await client.GetAsync(client.BaseAddress);//Here is where everything stops

            response.EnsureSuccessStatusCode();
            client.Dispose();

            string jsonResult = await response.Content.ReadAsStringAsync();
            return jsonResult;
        }

        public async Task<string> PostUser(UserModel User_Raw)
        {
            try
            {
                var client = new HttpClient()
                {
                    BaseAddress = new Uri("Here goes the url")
                };

                var user = JsonConvert.SerializeObject(User_Raw);
                var stringUser = new StringContent(user, UnicodeEncoding.UTF8, "application/json");

                var response = await client.PostAsync(client.BaseAddress, stringUser); //Here is where everything stops
                response.EnsureSuccessStatusCode();

                string HttpResponse = await response.Content.ReadAsStringAsync();
                return HttpResponse;
            }
            catch(Exception error) //It never enters this section
            {
                return error.ToString();
            }
        }
    }

PostUser()中需要User_Raw:

try
    {
                        UserModel user = new UserModel() //UserModel is where I made the change described before
                        {
                            username = "username", 
                            password = "password", 
                            email = "email", 
                            phoneNumber = "phoneNumber"
                        };
                        string result = await apiDataBase.PostUser(user);
                    }
                    catch
                    {
                        string a = "'";
    }

[我已经在其他帖子中看到了这个问题,但是答案都不同,似乎没有一个适合我。

仅此,如果您需要更多信息,我将在收到您的请求后将其提供给您,谢谢您的时间,希望您过得愉快。

c# asp.net-core xamarin.forms get httprequest
1个回答
0
投票

首先,请阅读有关HttpClient的文档,因为使用您的代码,您将发出多个请求。这最终会削弱您的应用程序。然后,您可以使用此示例方法来请求json字符串

© www.soinside.com 2019 - 2024. All rights reserved.