Xamarin表格发布请求Http问题

时间:2017-09-13 15:59:36

标签: c# asp.net-mvc xamarin http-post dotnet-httpclient

我正在使用我的Xamarin表单发送POST请求,以便将数据发送到我的WebAPI项目中的控制器中的Action。带断点的代码不会超出

client.BaseAddress = new Uri("192.168.79.119:10000");

我有命名空间System.Net.Http并使用代码中提到的System。

 private void BtnSubmitClicked(object sender, EventArgs eventArgs)
    {
        System.Threading.Tasks.Task<HttpResponseMessage> statCode = ResetPassword();
        App.Log(string.Format("Status Code", statCode));


    }
    public async Task<HttpResponseMessage> ResetPassword()
    {
        ForgotPassword model = new ForgotPassword();
        model.Email = Email.Text;
        var client = new HttpClient();

        client.BaseAddress = new Uri("192.168.79.119:10000");

        var content = new StringContent(
           JsonConvert.SerializeObject(new { Email = Email.Text }));

        HttpResponseMessage response = await client.PostAsync("/api/api/Account/PasswordReset", content); //the Address is correct

        return response;
    }

需要一种方法向该Action发出Post请求并将该String或Model.Email作为参数发送。

1 个答案:

答案 0 :(得分:2)

您需要使用正确的Uri,并且await从被调用的方法返回任务。

private async void BtnSubmitClicked(object sender, EventArgs eventArgs) {
    HttpResponseMessage response = await ResetPasswordAsync();
    App.Log(string.Format("Status Code: {0}", response.StatusCode));
}

public Task<HttpResponseMessage> ResetPasswordAsync() {
    var model = new ForgotPassword() {
        Email = Email.Text
    };
    var client = new HttpClient();
    client.BaseAddress = new Uri("http://192.168.79.119:10000");
    var json = JsonConvert.SerializeObject(model);
    var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
    var path = "api/api/Account/PasswordReset";
    return client.PostAsync(path, content); //the Address is correct
}