检测Web服务发布的时间

时间:2014-02-12 18:31:06

标签: windows-phone-8

我刚写了一个简单的windows 8表单,发布到web服务api。它工作正常。但我的挑战是能够确定后期操作何时成功和失败。我不知道如何返回值cos aysnc任务不允许返回类型。

//This class does the post to web service 
public class B2cMobileuserService : IB2cMobileuserService
    {
        private  string RegisterUserUrl = RestfulUrl.RegisterMobileUser;
        private readonly HttpClient _client = new HttpClient();


        public async Task RegisterMobileUser(B2cMobileuserView user)
        {
            var jsonString = Serialize(user);
            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var result = await _client.PostAsync(RegisterUserUrl, content);           
        }
}


//This class calls the one above

 public class WebserviceProcessor
    {
        //declaring all the service objects that would be used
        IB2cMobileuserService mobileuserService = null;

        public WebserviceProcessor() {
            mobileuserService = new B2cMobileuserService();
        }


        //This method is going to post values to the web serever
        public async void RegisterUser(B2cMobileuserView mobileuser) {
           mobileuserService.RegisterMobileUser(mobileuser);
        }


    }



//Then the code below is from my .xaml user interface that calls the class that sends to webservice

  private void Button_Click(object sender, RoutedEventArgs e)
        {
            B2cMobileuserView user = new B2cMobileuserView();
            user.Name = name.Text;
            user.Email = email.Text;
            user.PhoneType = "Windows Mobile";
            user.BrowserType = "None";
            user.CountryName = "Nigeria";
            user.UserPhoneID = phone.Text;

            Serviceprocessor.RegisterUser(user);

            progressBar.Visibility = Visibility.Visible;
        }


Please I dont know how to return a value cos when I try I get the error that says async method must be void. 
I need to set a way to know when the post was a success based on the return value from the web service.

1 个答案:

答案 0 :(得分:0)

要确保POST成功,请致电HttpResponseMessage.EnsureSuccessStatusCode

public async Task RegisterMobileUser(B2cMobileuserView user)
{
  var jsonString = Serialize(user);
  var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
  var result = await _client.PostAsync(RegisterUserUrl, content);           
  result.EnsureSuccessStatusCode();
}

如果要返回值,请使用Task<T>返回类型而不是Task

在旁注中,请避免async void;使用async Task代替async void,除非编译器强制你写async void

//This method is going to post values to the web serever
public Task RegisterUser(B2cMobileuserView mobileuser) {
  return mobileuserService.RegisterMobileUser(mobileuser);
}

此外,您应该命名以*Async结尾的异步方法:

//This method is going to post values to the web serever
public Task RegisterUserAsync(B2cMobileuserView mobileuser) {
  return mobileuserService.RegisterMobileUserAsync(mobileuser);
}

您可能会发现我的async introMSDN article on async best practices有帮助。