Xamarin Forms安卓模拟器无法访问本地部署的ASP.NET Web API接口
问题描述
我正在开发一款基于ASP.NET Web Application模板的Xamarin Forms应用,目前遇到PostAsync方法调用失败的问题:本地通过IIS启动Web API后用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方法的UserService服务类
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序列化的ModelAccount类
class ModelAccount { public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } }
相关配置截图
- Web API属性配置:

- 端口配置:

已尝试的解决方案
参考相关技术文档的建议将端口号修改为61902后,问题仍未解决,请求协助排查。
内容的提问来源于stack exchange,提问作者RoyJ
相关产品推荐
相关产品推荐

