在 JSON 中获得 400 webservice 状态时返回 false

returning a false when got 400 status of webservice in JSON

在我的代码隐藏文件中,我调用了这个函数:

private void loginAction(object sender, TappedRoutedEventArgs e)
{
    Webservice webservice = new Webservice();
    webservice.getUser(txtLogin.Text, txtPass.Text);
}

然后在网络服务中我这样做:

public void getUser(String user, String password)
{
    String strUrl = String.Format("http://*******/nl/webservice/abc123/members/login?email={0}&password={1}",user,password);

    startWebRequest(strUrl, loginCallback);
}

private async void loginCallback(IAsyncResult asyncResult)
{
    try
    {
        ReceiveContext received = GetReceiveContextFromAsyncResult(asyncResult, "User");

        if (received != null && received.Status == 200)
        {
            await UserDataSource.AddUser(received.Data);
        }
        else
        {

            throw new Exception("failedddd");
        }
    }
    catch (Exception e)
    {

    }   
}

我现在要做的是当抛出异常时,显示一个消息框。当我获得状态 200 时,我导航到 de code behind 文件中的下一页。

我现在的问题是,我如何在我的代码隐藏文件中知道这一点?

非常感谢!

编辑 我还有这些辅助方法:

#region HELPERS
private void startWebRequest(string url, AsyncCallback callback)
{
    // HttpWebRequest.RegisterPrefix("http://",WebRequestCreator.ClientHttp);
    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

    // start the stream immediately
    httpWebRequest.AllowReadStreamBuffering = false;

    // asynchronously get a response
    httpWebRequest.BeginGetResponse(callback, httpWebRequest);
}

private ReceiveContext GetReceiveContextFromAsyncResult(IAsyncResult asyncResult, string context)
{
    // Request afleiding van de AsyncState uit het ontvangen AsyncResult
    HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse httpWebResponse = null;

    try
    {
        // Response afleiden uit de Resuest via de methode EndGetResponse();
        httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);

        string responseString;
        // using == IDisposable (automatische GC)
        using (StreamReader readStream = new StreamReader(httpWebResponse.GetResponseStream()))
        { //Stream van de response gebruiken om een readstream te maken.
            responseString = readStream.ReadToEnd();
        }
        // Release the HttpWebResponse
        //httpWebResponse.Dispose();

        return new ReceiveContext(int.Parse(responseString.Substring(10, 3)), responseString);
    }
    catch (WebException wex)
    {
        Debug.WriteLine(String.Format("{0} kon niet opgehaald worden: {1}", context, wex.Message));
    }
    catch (JsonReaderException jrex)
    {
        Debug.WriteLine(String.Format("{0} opgehaald van server, maar de json kon niet geparsed worden: {1}", context, jrex.Message));
    }
    catch (FormatException fex)
    {
        Debug.WriteLine(String.Format("{0} opgehaald van server, maar de gegevens kloppen niet: {1}", context, fex.Message));
    }
    catch (ArgumentOutOfRangeException arex)
    {
        Debug.WriteLine(String.Format("{0} opgehaald van server, maar de context is leeg: {1}", context, arex.Message));
    }

    return null;
}
public sealed class ReceiveContext
{
    public ReceiveContext(int status, string data)
    {
        this.Status = status;
        this.Data = data;
    }

    public int Status { get; private set; }

    public string Data { get; private set; }
}
#endregion 

下面的代码使用API Windows.Web.Http.HttpClient(微软推荐使用这个API连接REST服务)

public class Result
{
    public HttpStatusCode Status { get; set; }
    public string Data { get; set; }
}

public async Task<Result> LoginAsync(string user, string password)
{
    var http = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://*******/nl/webservice/abc123/members/login?email="+ user + "&password="+ password));
    var result = await http.SendRequestAsync(request);

    var data = new Result {Status = result.StatusCode};
    if (result.StatusCode== HttpStatusCode.Ok && result.Content!=null)
    {
        data.Data = await result.Content.ReadAsStringAsync();
    }
    return data;
}

在你后面的代码中:

var result2 = await LoginAsync("", "");
if (result2.Status == HttpStatusCode.Ok)
{
    //Status code 200
    //navigate to other page
}
else if(result2.Status == HttpStatusCode.BadRequest)
{
    //Status code 400
    //your code
}

由于您收到 Json 回复,建议您首先将 Newtonsoft nuget 包添加到您的项目中。
之前我们曾经添加服务引用,但现在我们可以使用

轻松完成
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://*******/nl/webservice/abc123/members/login?email="+ user + "&password="+ password));
var resultlogin = await response.Content.ReadAsStringAsync(); //this is usually string type
var obj = JsonConvert.DeserializeObject<UserLogin.RootObject>(resultbrand);
//I usually define my own custom C# class using json2csharp.com or you can use Json.Deserialize also.

class UserLogin
{
    public class User
    {
        public string UserName { get; set; }
        public string Email { get; set; }
    }

    public class RootObject
    {
        public string tag { get; set; }
        public int success { get; set; }
        public int error { get; set; }
        public string uid { get; set; }
        public User User { get; set; }
    }
} 

现在最重要的命名空间应该是

using System.Net.Http;

而不是

using Windows.Web.Http;