我正在开发一个使用 ASP.NET Web 应用程序模板的 Xamarin 表单应用程序。我在 YouTube 上关注了这个教程。我在使用 PostAsync 方法时遇到问题。web api 本身可以通过我本地机器上的 IIS Chrome 启动,但不能通过模拟器启动。我打印了响应消息,显示为
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:
System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Server: Microsoft-HTTPAPI/2.0
Date: Sun, 26 Sep 2021 06:53:22 GMT
Connection: close
Content-Type: text/html; charset=us-ascii
Content-Length: 334
}
这是包含 RegisterAsync 方法的服务类
public class UserService
{
private string androidApiUrl = "https://10.0.2.2:44358/api/Account/Register";
private string iOSApiUrl = "https://localhost:44358/api/Account/Register";
private HttpClient client;
public UserService()
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback =
(msg, cert, chain, err) => { return true; };
client = new HttpClient(httpClientHandler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<bool> RegisterAsync(string username, string pswd, string confmPswd)
{
var newAccount = new ModelAccount
{
Email = username,
Password = pswd,
ConfirmPassword = confmPswd
};
var json = JsonConvert.SerializeObject(newAccount);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
try
{
var response = await client.PostAsync(androidApiUrl, content);
Console.WriteLine(response.ToString());
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response);
return response.IsSuccessStatusCode;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw e;
}
}
}
这是 json 序列化的 ModelConvert。
class ModelAccount
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
如果我按照本博客的建议将端口号更改为 61902 会有所不同,它仍然无法正常工作。
谢谢
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句