本文示範如何在 ASP.NET Web API 專案中構造標準 application/x-www-form-urlencoded POST 請求,並建立對應的 Controller 接收模型綁定資料,完成客戶端與伺服端完整交互流程。
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 才能自動綁定。
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);
}
}
}
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-Type | application/x-www-form-urlencoded (表單) 或 application/json (JSON API) |
| 模型綁定 | Web API 自動從請求體反序列化到 Action 參數型別 (需公共屬性 Setter) |
| 非同步 | Client 端強烈建議使用 HttpClient + async/await,避免阻塞執行緒 |
| HttpClient 重用 | 應為 Singleton 或靜態實例,避免 Socket 耗盡 |
| 錯誤處理 | 檢查 response.IsSuccessStatusCode,讀取錯誤內容 ReadAsStringAsync |
若 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) { ... }
Microsoft.AspNet.WebApi.Tracing 記錄請求/響應細節。Content-Type 標頭是否與實際發送內容一致。掌握標準 POST 請求構造與模型綁定機制,是 Web API 開發與整合第三方服務 (OAuth、支付、簡訊 API) 的基礎技能。