【发布时间】:2020-04-07 14:53:09
【问题描述】:
我在这里有 2 个应用程序。一个是 Xamarin 应用程序,另一个是 Asp.Net MVC 应用程序,它具有 WebApi 以连接到 SqlServer 数据库“其中数据库位于某个 IP 地址 xxx.xxx.xxx.xxx 的托管网站上”。
我在 IIS 中本地运行 MVC 应用程序,然后在 IIS 中启动网站后,我从 Visual Studio 的第二个实例运行 Xamarin 应用程序。
首先,我不认为 MVC WebApi 被调用,因为我尝试将断点放在那里,但它没有出现。我不知道为什么。因为我对 Winforms 和 MVC 应用程序 (WebApi) 做了同样的事情,所以至少 WebApi 被调用了,我在 MVC 应用程序中看到了断点。
现在在 Xamarin 中出现此错误
System.Net.Http.HttpRequestException: 'Network subsystem is down'
在行中
var responseTask = await client.GetAsync("ConnectToAscDatabase");
我在 Xamarin 应用程序的 MainPage.cs 中有这段代码
private async void Button_OnClicked(object sender, EventArgs e)
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:49252/api/");
// !!! This Line gives the error System.Net.Http.HttpRequestException: 'Network subsystem is down'
var responseTask = await client.GetAsync("ConnectToAscDatabase");
var readTask = responseTask.Content.ReadAsAsync<Microsoft.Data.SqlClient.SqlConnection>();
SqlConnection con = readTask.Result;
var staty = con.State;
}
}
这是一个 WebApi
public class ConnectToAscDatabaseController : ApiController
{
public async Task<Microsoft.Data.SqlClient.SqlConnection> Get()
{
string SqlServer_ServerPath_Server = "SomeServer";
string SqlServer_Database_Server = "SomeDatabase";
string SqlServer_User_Server = "SomeUser";
string SqlServer_Password_Server = "SomePassword";
int timeOutInSeconds = 15;
string connectionString = "data source=" + SqlServer_ServerPath_Server + ";" + "initial catalog=" + SqlServer_Database_Server + ";" + "user id=" + SqlServer_User_Server + ";" + "Password=" + SqlServer_Password_Server + ";" + "Trusted_Connection=false" + ";" + "Connection Timeout=" + timeOutInSeconds + ";" + "Persist Security Info=False";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
return con;
}
}
【问题讨论】:
-
你用的是安卓模拟器吗?
-
不要使用本地主机。使用您的服务器的 IP。并确保您的本地 IIS 配置为允许外部连接
-
是的,我正在使用 Android 模拟器
-
"localhost" 会告诉安卓模拟器连接回它自己,而不是你的本地服务器。这就是您应该使用 IP 的原因。
-
Jason 我尝试使用我的实时网站 URL client.BaseAddress = new Uri("example.com/api/"); 我没有收到错误,但返回的连接对象包含所有 ConnectionString、State 和 ALL属性为 NULL(更具体地说,它说“System.NullReferenceException:对象引用未设置为对象的实例”与 Connection 对象中的所有值相反。
标签: c# xamarin asp.net-web-api2