萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Web API 實作 POST 請求構造與客戶端/伺服端完整交互範例

本文示範如何在 ASP.NET Web API 專案中構造標準 application/x-www-form-urlencoded POST 請求,並建立對應的 Controller 接收模型綁定資料,完成客戶端與伺服端完整交互流程。

專案結構

  • Client 專案:ASP.NET MVC 5 (模擬呼叫端)
  • Server 專案:ASP.NET Web API 2 (接收端)
  • 兩個 IIS Express 實例並行運行 (不同 Port)

Server 端:Web API Controller

1. 定義請求模型 (Model Binding 必備)

namespace Server.Models
{
    public class OAuthRequestArgs
    {
        public string ClientId { get; set; }       // 對應 client_id
        public string RedirectUri { get; set; }    // 對應 redirect_uri
        public string ResponseType { get; set; }   // 對應 response_type
    }
}

關鍵: 屬性名稱必須與表單欄位名稱完全對應 (不區分大小寫),Model Binder 才能自動綁定。

2. Controller Action

namespace Server.Controllers
{
    public class ApiTestController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage Post(OAuthRequestArgs args)
        {
            if (args == null) 
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid request body");

            // 業務邏輯處理...
            string msg = $"Received: client_id={args.ClientId}, redirect_uri={args.RedirectUri}, response_type={args.ResponseType}";
            
            return Request.CreateResponse(HttpStatusCode.OK, msg);
        }
    }
}

Client 端:MVC Controller 發送 POST

namespace Client.Controllers
{
    public class HomeController : Controller
    {
        public async Task<ActionResult> Index()
        {
            string serverUrl = "https://localhost:14340/api/ApiTest"; // Server 實際 URL
            
            // 1. 構造表單資料
            var formData = new Dictionary<string, string>
            {
                { "client_id", "123" },
                { "redirect_uri", "https://client.com/callback" },
                { "response_type", "code" }
            };
            
            // 2. 使用 HttpClient (現代、非同步、建議方式)
            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(formData);
                var response = await client.PostAsync(serverUrl, content);
                
                string result = await response.Content.ReadAsStringAsync();
                ViewBag.Response = result;
            }

            /* 
            // 舊式 HttpWebRequest 寫法 (僅供參考)
            var request = (HttpWebRequest)WebRequest.Create(serverUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string body = "client_id=123&redirect_uri=...&response_type=code";
            byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
            using (var stream = request.GetRequestStream())
                stream.Write(bodyBytes, 0, bodyBytes.Length);
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
                ViewBag.Response = reader.ReadToEnd();
            */

            return View();
        }
    }
}

關鍵技術點總結

項目說明
Content-Typeapplication/x-www-form-urlencoded (表單) 或 application/json (JSON API)
模型綁定Web API 自動從請求體反序列化到 Action 參數型別 (需公共屬性 Setter)
非同步Client 端強烈建議使用 HttpClient + async/await,避免阻塞執行緒
HttpClient 重用應為 Singleton 或靜態實例,避免 Socket 耗盡
錯誤處理檢查 response.IsSuccessStatusCode,讀取錯誤內容 ReadAsStringAsync

進階:JSON 格式 POST

若 API 規範使用 JSON:

// Client
var json = JsonConvert.SerializeObject(new { client_id = "123", ... });
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);

// Server Action 參數型別不變,Web API 內建 JSON Formatter 會自動反序列化
public HttpResponseMessage Post(OAuthRequestArgs args) { ... }

除錯技巧

  1. 使用 Postman 或 Fiddler 獨立測試 Server API,隔離 Client 問題。
  2. Server 端啟用 Microsoft.AspNet.WebApi.Tracing 記錄請求/響應細節。
  3. 檢查 Content-Type 標頭是否與實際發送內容一致。

掌握標準 POST 請求構造與模型綁定機制,是 Web API 開發與整合第三方服務 (OAuth、支付、簡訊 API) 的基礎技能。

copyright © 萬盛學電腦網 all rights reserved