ASP.NET - 後端呼叫API (HttpClient)

  • 7918
  • 0

寫慣網頁,總是靠前端指定網址,透過瀏覽器呼叫對應網址,如果開發如純後端的測試則無法透過瀏覽器瀏覽

因此使用System.net.httmp下的物件 "HttpClient"

先來看Template


using (var client = new HttpClient())
{
    //設定基底URI
    client.BaseAddress = new Uri("http://localhost:59863/");   

    //Initializes a new instance of the HttpRequestMessage class with an HTTP method and a request Uri
    HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, "api/controler/action"); 
    
    //或採用如下
    //HttpRequestMessage request = new HttpRequestMessage();
    //request.Method = HttpMethod.Post;
    //request.RequestUri = new Uri("api/controler/action");

    //設定Header
    //request.Headers.Add("name", "value");

    //設定body內容和格式
    request.Content = new StringContent(JsonArticle, Encoding.UTF8, "application/json");



    var response = client.SendAsync(request).Result;

    //判斷是否連線成功
    if (response.IsSuccessStatusCode) 
    {
        //取回傳值
        var APIResult = response.Content.ReadAsAsync<string>().Result;
    }
};