【发布时间】:2018-07-31 21:05:44
【问题描述】:
我创建了包含身份验证的 .NET Framework API,我使用 Jetbrains Rider 启动了 Web API,我使用 Visual Studio 运行了我的 Xamarin.Forms 应用程序,我无法从我的 Web API 访问任何数据,也无法发布任何数据。
Webservice 类:
private readonly HttpClient _client;
public AccountService()
{
_client = new HttpClient
{
MaxResponseContentBufferSize = 256000
};
}
public async Task RegisterAsync(string email, string password, string confirmPassword)
{
var url = "http://169.254.80.80:61348/api/Account/Register";
var model = new RegisterBindingModel()
{
Email = email,
Password = password,
ConfirmPassword = confirmPassword
};
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await _client.PostAsync(url, content);
}
开始注册
private async void Register()
{
try
{
using (UserDialogs.Instance.Loading())
{
await _accountServices.RegisterAsync
(Email, Password, ConfirmPassword);
}
UserDialogs.Instance.Alert("Register Successful");
await _navigation.PushAsync(new LoginPage());
}
catch
{
UserDialogs.Instance.Alert("Something wrong happened, Try again");
}
}
我尝试使用这些 IP 通过 Emulator 访问本地主机:
- 10.0.3.2
- 10.0.2.2
- 169.254.80.80
我已经尝试了我的默认网关和我的本地 IP 地址,无论是否使用端口,无论使用邮递员,我都可以完美地使用我的 api。
我没有收到错误但连接状态码不成功并且我没有收到任何数据并且新注册的帐户不会发布到api。
编辑: 至于答案,我已将方法更改为:
public async Task<string> RegisterAsync(string email, string password, string confirmPassword)
{
var client = new HttpClient()
{
BaseAddress = new Uri("http://169.254.80.80:61348/")
};
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("email", email));
nvc.Add(new KeyValuePair<string, string>("password", password));
nvc.Add(new KeyValuePair<string, string>("confirmPassword", confirmPassword));
var req = new HttpRequestMessage(HttpMethod.Post, "api/Account/Register") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
string test = JsonConvert.DeserializeObject<string>(result);
return test;
}
return null;
}
我使用 postman 调用 web api,如下所示: http://localhost:61348/api/Account/Register
【问题讨论】:
-
postman中如何传递参数来注册用户?
-
只是 json 属性电子邮件和密码以及确认密码
标签: rest xamarin xamarin.forms localhost visual-studio-emulator