http GET / Post完成后的C#回调

时间:2015-03-24 08:38:44

标签: .net windows-phone-8.1 task c#-5.0

我希望我的注册课能够确定我服务器的响应。为了实现这一点,需要从我的Newtwork Client类Request Handler创建某种形式的回调。我无法弄清楚如何最好地实现这一目标。下面是我的工作代码。下面是我想要从Objective-C

模拟的内容
public class SignUp{
 private async void createUser()
    {
        RequestHandler client = new RequestHandler();
        CreatePerson person = new CreatePerson();
        person.FirstName=this.firstNameText.Text;
        person.LastName=this.lastNameText.Text;
        person.Location="POINT(0 0)";
        person.Major = this.majorText.Text;
        person.UserName = this.userNameText.Text;
     //   person.Major =;
    await RequestHandler.CreatePerson(person);


    }
}

请求处理程序类

 public class RequestHandler
    {


   public static async Task CreatePerson(CreatePerson person)
           {
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://studytree2.azurewebsites.net/api/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response;
        // HTTP POST

        response = await client.PostAsJsonAsync("Profile/CreateProfile", person );
        if (response.IsSuccessStatusCode)
        {

        }
    }
          }
    }

OBJECTIVE-C代码

-(void)CreateUser
{
 [load doAlert:@"Registering" body:@"Submitting..." duration:0 done:^(DoAlertView *alertView) {

}];

[[RequestHandler shared]createPersonUsername:userNameText Firstname:firstName Lastname:lastName Password:passwordText Email:emailText Major:major success:^{
        [load hideAlert];

        if(currentImage !=nil)
        {
            [postPhoto postimageProfileImage:currentImage];
        }

    [self dismissViewControllerAnimated:YES completion:^{
        [self.delegate SignUpDidCompleteSuccess];
    }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [load hideAlert];
        DoAlertView * alert =[[DoAlertView alloc]init];

        alert.bDestructive=YES;
        NSString * errorString;
        if(operation.response.statusCode==409)
        {
            errorString=@"Email already registered";
        }
        else if(operation.response.statusCode==405)
        {
            errorString=@"User name already exist";
        }
        else if(operation.response.statusCode==501)
        {
            errorString=@"Your university is not supported yet. :(";
        }
        else if(operation.response.statusCode == 415)
        {
            errorString=@"Your email is not valid. Please enter a active email";
        }
        else
        {
            errorString=@"Could not register (check connection)";
        }

        [alert doYes:errorString yes:^(DoAlertView *alertView) {

        }];
    }];

在Objective C中创建RequestHandler

 -(void)createPersonUsername:(NSString *)username Firstname:(NSString  *)firstname Lastname:(NSString *)lastName Password:(NSString *)password Email: (NSString *)email Major:(NSString *)major success:(void (^)())successBlock  failure:(void (^)(AFHTTPRequestOperation *, NSError *))failureBlock
  {
 double x= [LocationTracker   sharedLocationManager].location.coordinate.longitude;
 double y= [LocationTracker sharedLocationManager].location.coordinate.latitude;
  NSString * locationString =[NSString stringWithFormat:@"POINT(%f %f)",x,y ];
  NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:username,@"UserName",firstname,@"FirstName",password,@"Password",email,@"Email",lastName,@"LastName",major,@"Major",locationString, @"location", nil];
NSURL *baseUrl=[NSURL URLWithString:KBaseUrl];

manager = [[AFHTTPRequestOperationManager manager]initWithBaseURL:baseUrl];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
 [manager POST:@"/api/Profile/CreateProfile" parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {

     successBlock();
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     failureBlock(operation,error);

 }];
}

1 个答案:

答案 0 :(得分:1)

我对Objective-C了解不多,但在C#中你可以通过使用事件

来实现
public class RequestHandler
{
    //Need to create event Handler
    public event EventHandler DataReceivedHandler = null;


    public async Task CreatePerson(CreatePerson person)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://studytree2.azurewebsites.net/api/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response;
            // HTTP POST

            response = await client.PostAsJsonAsync("Profile/CreateProfile", person);
            if (response.IsSuccessStatusCode && DataReceivedHandler!=null)
            {
               var responseBodyAsText = response.Content.ReadAsStringAsync().Result;

               DataReceivedHandler(this, new ResponseData { Data = responseBodyAsText });
            }
        }
    }
}




public class SignUp
{
    private async void createUser()
    {
        RequestHandler client = new RequestHandler();
        CreatePerson person = new CreatePerson();
        person.FirstName = this.firstNameText.Text;
        person.LastName = this.lastNameText.Text;
        person.Location = "POINT(0 0)";
        person.Major = this.majorText.Text;
        person.UserName = this.userNameText.Text;
        //   person.Major =;
        client.DataReceivedHandler += client_DataReceivedHandler;
        await client.CreatePerson(person);


    }

    void client_DataReceivedHandler(object sender, EventArgs e)
    {
        // this event trigger when your web request complete.
        throw new NotImplementedException();
    }
}

您需要进行一些修改,但我正在为我的应用程序使用相同的代码......并且其工作正常。希望这会对你有所帮助。