C# (ASP.NET Web API / WCF / ASMX) 暴露 HTTP 端點 → **Android (OkHttp / Retrofit / Volley / 原生 HttpURLConnection)** 發起請求 → JSON 數據交換。核心是 **HTTP + JSON**,跨平台、跨語言無障礙。
dotnet new webapi -n MyApi
cd MyApi
// Models/User.cs
public class User { public int Id { get; set; } public string Name { get; set; } }
// Controllers/UsersController.cs
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase {
private static readonly List<User> _users = new() { new User { Id = 1, Name = "張三" } };
[HttpGet]
public ActionResult<IEnumerable<User>> Get() => Ok(_users);
[HttpGet("{id}")]
public ActionResult<User> Get(int id) {
var user = _users.FirstOrDefault(u => u.Id == id);
return user == null ? NotFound() : Ok(user);
}
[HttpPost]
public ActionResult<User> Post(User user) {
user.Id = _users.Max(u => u.Id) + 1;
_users.Add(user);
return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
}
}
dotnet run 默認監聽 https://localhost:5000。launchSettings.json 或命令行 dotnet run --urls "https://0.0.0.0:5000"。// Service.asmx.cs
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class UserService : System.Web.Services.WebService {
[WebMethod]
public User GetUser(int id) {
return new User { Id = id, Name = "李四" };
}
}
// User.cs
public class User { public int Id; public string Name; }
訪問 https://host/Service.asmx/GetUser?id=1 返回 XML/JSON (取決於 Accept 頭)。
<uses-permission android:name="android.permission.INTERNET" />
<!-- Android 9+ 明文 HTTP 需配置 network_security_config -->
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://192.168.1.100:5000/api/users/1") // 替換為實際 PC 局域網 IP
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace(); // 網絡錯誤
}
@Override public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
// 解析 JSON (Gson/Moshi) -> 更新 UI (runOnUiThread)
Log.d("API", "Response: " + json);
}
}
});
// ApiService.java
public interface ApiService {
@GET("api/users/{id}")
Call<User> getUser(@Path("id") int id);
@POST("api/users")
Call<User> createUser(@Body User user);
}
// User.java (與 C# 模型字段一致)
public class User { public int id; public String name; }
// 使用
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://192.168.1.100:5000/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
service.getUser(1).enqueue(new Callback<User>() {
@Override public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
User user = response.body();
// 更新 UI
}
}
@Override public void onFailure(Call<User> call, Throwable t) { t.printStackTrace(); }
});
https://PC_IP:端口/api/users。10.0.2.2 映射宿主機,真機必須用 **PC 局域網 IP** (ipconfig 獲取)。res/xml/network_security_config.xml 允許明文,或上 HTTPS (Let's Encrypt + 內網穿透/正式域名)。[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 或配置 web.config。JsonIgnore 或 ReferenceHandler.Preserve。C# 寫 Web API 極簡 (ASP.NET Core 幾十行),Android 用 Retrofit/OkHttp 調用極穩。**核心不在語言,而在 HTTP/JSON 協議契約與網絡連通性**。先用瀏覽器驗證接口,再寫客端代碼,能節省 90% 排查時間。