在JSON中获得Webservice的400状态时返回一个false如何解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (64)

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

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

然后在web服务中,我这样做:

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时,我会导航到代码隐藏文件的下一页。

我的问题是现在,我如何知道这在我的代码背后的文件?

我也有这些帮手方法:

#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(Microsoft建议使用此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;

扫码关注云+社区