首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 編寫 WebService 供 Android 通過 HTTP 調用:原理與實戰演示

     編輯:程式設計疑難解答

整體架構

C# (ASP.NET Web API / WCF / ASMX) 暴露 HTTP 端點 → **Android (OkHttp / Retrofit / Volley / 原生 HttpURLConnection)** 發起請求 → JSON 數據交換。核心是 **HTTP + JSON**,跨平台、跨語言無障礙。

方案一:ASP.NET Core Web API (現代、推薦)

1. 創建項目

dotnet new webapi -n MyApi
cd MyApi

2. 定義模型與控制器

// 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);
    }
}

3. 發布與防火牆

  • 本地測試:dotnet run 默認監聽 https://localhost:5000。
  • 局域網訪問:修改 launchSettings.json 或命令行 dotnet run --urls "https://0.0.0.0:5000"。
  • 關鍵:Windows 防火牆開放 5000 端口 (入站規則 → 新規則 → 端口 → TCP 5000 → 允許)。

方案二:傳統 ASMX WebService (老項目維護)

// 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 頭)。

Android 端調用實戰

1. 權限

<uses-permission android:name="android.permission.INTERNET" />
<!-- Android 9+ 明文 HTTP 需配置 network_security_config -->

2. OkHttp 簡單 GET (推薦用 Retrofit 封裝)

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);
        }
    }
});

3. Retrofit 2 完整示例 (生產級)

// 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(); }
});

調試核心原則:瀏覽器先行

  1. 在 **Android 設備瀏覽器** 訪問 https://PC_IP:端口/api/users。
  2. 能看到 JSON 返回 → 服務端、網絡、防火牆全通。
  3. 瀏覽器 404/連接超時 → 檢查 C# 服務是否運行、IP 是否正確、防火牆是否放行、是否綁定 0.0.0.0。
  4. 瀏覽器正常但 App 失敗 → 檢查 Android 網絡安全配置 (明文 HTTP)、代碼邏輯、線程處理。

常見坑點總結

  • 用 localhost/127.0.0.1:Android 模擬器用 10.0.2.2 映射宿主機,真機必須用 **PC 局域網 IP** (ipconfig 獲取)。
  • HTTP 明文被 Android 9+ 攔截:配置 res/xml/network_security_config.xml 允許明文,或上 HTTPS (Let's Encrypt + 內網穿透/正式域名)。
  • C# 返回 XML 而非 JSON:ASP.NET Core 默認 JSON;ASMX 需設置 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 或配置 web.config。
  • 序列化循環引用:實體類含導航屬性時配置 JsonIgnore 或 ReferenceHandler.Preserve。

總結

C# 寫 Web API 極簡 (ASP.NET Core 幾十行),Android 用 Retrofit/OkHttp 調用極穩。**核心不在語言,而在 HTTP/JSON 協議契約與網絡連通性**。先用瀏覽器驗證接口,再寫客端代碼,能節省 90% 排查時間。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved