简体   繁体   English

WP8.1客户端代码中的HttpResponseMessage错误

[英]HttpResponseMessage error in WP8.1 client code

I have a problem that I can't seem to figure out with my WindowsPhone 8.1 app. 我有一个我似乎无法使用WindowsPhone 8.1应用解决的问题。 On my client side, I'm writing code to retrieve the values from the database that I query. 在客户端,我正在编写代码以从查询的数据库中检索值。 While I was able to successfully do that with my Bars entities, I can't seem to get my Teams entities to work. 虽然我可以通过Bars实体成功完成此操作,但似乎无法让Teams实体正常工作。 The weird thing is that it seems to both get past and get stuck on the creation of my HttpResponseMessage object. 奇怪的是,它似乎既过去又被我的HttpResponseMessage对象的创建所卡住。 Here's the code: 这是代码:

private void refresh_Click(object sender, RoutedEventArgs e)
    {
        GetTeams();
        //getTeamById(10);
    }


    public async void GetTeams()
    {
        using (var client = new HttpClient())
        {
            teamsListBox.Items.Add("using block entered");
            client.BaseAddress = new Uri("http://nflff.azurewebsites.net");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            teamsListBox.Items.Add("client's defaultrequestheaders done");

            HttpResponseMessage response = await client.GetAsync("api/bars");//not getting past here
            teamsListBox.Items.Add("right after response"); //not printing
            if (response.IsSuccessStatusCode)
            {
                teamsListBox.Items.Add("if entered");
                //IList<Teams> Teams = await response.Content.ReadAsAsync<IList<Teams>>();
                string teams = await response.Content.ReadAsStringAsync();

                int start = 0;
                while (start != -1)
                {
                    start = stringToTeam(teams, start); //throwing exception inside stringToTeams, which isn't being called anywhere else
                }
            }
            teamsListBox.Items.Add(Teams.TeamsList.Count);
            foreach (var team in Teams.TeamsList)
            {
                teamsListBox.Items.Add(team.ToString());
            }
        }
    }

public int stringToTeam(String Team, int start)
    {
        start = Team.IndexOf("TeamID", start) + 8;
        int end = Team.IndexOf(",", start); //start index correct
        //teamsListBox.Items.Add(end);
        int id = Convert.ToInt32(Team.Substring(start, end - start)); //throws FormatException for string to DateTime
        //String id = Team.Substring(start, (end - start));
        teamsListBox.Items.Add("id is " + id);
        start = Team.IndexOf("TeamName", start) + 11;
        end = Team.IndexOf("\"", start);
        //teamsListBox.Items.Add(end);
        String name = Team.Substring(start, (end - start));
        teamsListBox.Items.Add("name is " + name);

        String city = Team.Substring(start, (end - start));
        teamsListBox.Items.Add("city is " + city);
        start = Team.IndexOf("TeamState", start) + 12;
        end = Team.IndexOf("\"", start);
        //teamsListBox.Items.Add(end);


        //creates a Teams model obj with values pulled from string and adds it to static list of objs in Teams model
        //teamsListBox.Items.Add(Teams.TeamsList.Count);
        Teams newTeam = new Teams(id, name, city);
        Teams.TeamsList.Add(newTeam);
        //teamsListBox.Items.Add(Teams.TeamsList.Count);
        //teamsListBox.Items.Add(newTeam.ToString());

        end += 4;
        if (end <= Team.Length)
        {
            return end;
        }
        else
        {
            return -1;
        }
    }

When I run this code, "right after response" isn't printing to the UI, whereas the test messages above them are. 当我运行这段代码时,“响应后”不会打印到UI,而上面的测试消息却是。 Also, the emulator will eventually break and throw a FormatException from a line within stringToTeam (which I'll post another question about), which isn't getting called anywhere else. 而且,仿真器最终将在stringToTeam(我将向其发布另一个问题)的一行中中断并引发FormatException,该异常在其他任何地方都不会被调用。 It's also worth mentioning that I have the exact same code for my Bars entity (with the names switched of course), and the bars works perfectly fine. 还值得一提的是,我的Bars实体具有完全相同的代码(当然,名称也已更改),并且bar可以正常工作。 I've compared every line of code in these methods as well as the models and server-side controllers, and they are exactly the same. 我已经比较了这些方法中的每一行代码以及模型和服务器端控制器,它们是完全相同的。 So why would the bars code work while the teams code doesn't? 那么,为什么条形码不能工作,而团队代码却不能工作呢?

If it helps, here's my model code: 如果有帮助,这是我的模型代码:

public class Teams
{
    private int teamID { get; set; }
    private string teamName { get; set; }
    private string teamCity { get; set; }
    //private object teamFlag { get; set; } //Janci, I was never able to see your comments.  What is teamFlag?  Is that their logo?
    public static List<Teams> TeamsList = new List<Teams>();

    public Teams(int id, string name, string city)
    {
        teamID = id;
        teamName = name;
        teamCity = city;
    }

    public override string ToString()
    {
        return "Team: " + teamID.ToString() + " " + teamName.ToString() + " City: " + teamCity;
    }
}

I have a SQL database hosted on an Azure website and I'm using .NET for my backend. 我有一个SQL数据库托管在Azure网站上,并且后端使用.NET。 Please help me figure out why my teams code won't work. 请帮助我弄清楚为什么我的团队代码无法正常工作。 Thanks. 谢谢。

I think the problem is here: 我认为问题出在这里:

HttpResponseMessage response = await client.GetAsync("api/bars");

Shouldn't it be: 不应该是:

HttpResponseMessage response = await client.GetAsync("api/teams");

The problem turned out to be that I had the wrong start and end indices in my stringToTeam method. 问题出在我的stringToTeam方法中,我的起点和终点索引错误。 Once I fixed that, the code worked and displayed properly. 一旦我解决了该问题,代码便可以正常工作并正确显示。 The method's IndexOf and Substring calls should look like the following: 该方法的IndexOf和Substring调用应如下所示:

        start = Team.IndexOf("TeamID", start) + 8;
        int end = Team.IndexOf(",", start); //start index correct
        //teamsListBox.Items.Add(end);
        int id = Convert.ToInt32(Team.Substring(start, end - start)); //throws FormatException for string to DateTime
        //String id = Team.Substring(start, (end - start));
        //teamsListBox.Items.Add("id is " + id);
        start = Team.IndexOf("TeamName", start) + 11;
        end = Team.IndexOf("\"", start);
        //teamsListBox.Items.Add(end);
        String name = Team.Substring(start, (end - start));
        //teamsListBox.Items.Add("name is " + name);
        start = Team.IndexOf("TeamCity", start) + 11;
        end = Team.IndexOf("\"", start);
        String city = Team.Substring(start, (end - start));

After hand-coding my own deserializer and tweaking it for each entity, I discovered the JsonConvert class. 对我自己的解串器进行手工编码并为每个实体进行调整之后,我发现了JsonConvert类。 I highly recommend against writing your own deserializer. 我强烈建议您不要编写自己的解串器。 Using JsonConvert, I can delete my stringToTeam() method and replace my old GetTeams() with the following: 使用JsonConvert,可以删除我的stringToTeam()方法,并用以下内容替换旧的GetTeams():

public async void GetTeams()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://nflff.azurewebsites.net");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/teams");//not getting past here

            if (response.IsSuccessStatusCode)
            {
                string s = await response.Content.ReadAsStringAsync();
                var deserializedResponse = JsonConvert.DeserializeObject<List<Teams>>(s);
                foreach (Teams team in deserializedResponse)
                {
                    teamsListBox.Items.Add(team.ToString());
                }

            }
            foreach (var team in Teams.TeamsList)
            {
                teamsListBox.Items.Add(team.ToString());
            }
        }
    }

This approach is far less tedious. 这种方法远没有那么乏味。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM