【发布时间】:2018-04-05 19:06:47
【问题描述】:
我的需求:将我的 Android 设备连接到本地 SQL Server 数据库。
我的问题:尝试连接时发生异常(“发送请求时发生错误”)
我使用的是:Visual Studio 2017 和具有 MVVM 架构的 Xamarin Forms。
什么有效:我从 Postman 发送了一个 POST,它运行良好,返回了用户的令牌。
我的项目使用 REST API 连接到数据库。 API 发布为 FileSystem 并使用 IISExpress 运行,正如我所说,它可以使用 Postman。
我试过了:
http://localhost:50965
http://192.168.1.106:50965(我的电脑IP)
我在 API Web.config 上的连接字符串
<add name="DefaultConnection" connectionString="Data Source=192.168.1.106; Initial Catalog=Gesuro; Integrated Security=True; User ID = sergio; Password=xxxxxxxx" providerName="System.Data.SqlClient" />
我对 API 的调用:
var token = await this.apiService.GetToken(
"http://localhost:50965",
this.Email,
this.Password);
我的 API 方法:
public async Task<TokenResponse> GetToken(
string urlBase,
string username,
string password)
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(urlBase);
var response = await client.PostAsync("Token",
new StringContent(string.Format(
"grant_type=password&username={0}&password={1}",
username, password),
Encoding.UTF8, "application/x-www-form-urlencoded"));
var resultJSON = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TokenResponse>(
resultJSON);
return result;
}
catch (Exception e)
{
var pepe = e.Message;
return null;
}
}
我已经在 Google 上搜索了三天并尝试了不同的解决方案……但没有结果。
我希望我的查询是具体的。请帮忙?
提前致谢。
【问题讨论】:
-
我不确定 Xamarin 是否存在与普通 Android 相同的问题,即:要通过物理设备连接到 localhost,您的设备和 PC 必须连接到同一个互联网(最好是 Wi-Fi),但您可以尝试将
localhost更改为 ip:10.0.2.2并尝试运行模拟器,因为 Xamarin 有这样的东西。 -
数据库是什么设备本地的?
-
您也可以尝试使用ngrok工具,在短时间内模拟真实服务器。它会为您生成随机 URL,然后您只需将
localhost替换为生成的任何 URLngrok,然后调用 API 试试运气。 -
不要使用本地主机。使用 IP 或 FQDN。并确保 IIS 设置为允许远程连接。
-
正如我在帖子中所写的,除了 localhost 之外,我已经尝试连接到我的 IP PC。数据库是 PC 本地的。我也试过模拟器。当我回到家时,我会尝试您向我提出的解决方案。
标签: android rest xamarin httpclient postman