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

C# Callback after http GET/Post completes

我希望我的注册 class 能够确定来自我的服务器的响应。为了实现这一点,需要从我的 Newtwork 客户端 class 请求处理程序创建某种形式的回调。我不知道如何最好地实现这一目标。下面是我的工作代码。下面正是我试图从 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);


    }
}

请求处理程序class

 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);

 }];
}

我不太了解 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();
    }
}

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