Post WebAPI using HttpClient
前言
隨手備份的Sample Code,不然懶人我每次要使用都得上網查找
↓ ASP.NET Core 2.1+
先自訂義一個自用的Helper類別
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;//須先透過Nuget加入此參考
namespace MyCentralizedWebAPI.Helper
{
public class MyWebHelper
{
private readonly IHttpClientFactory _clientFactory;
public MyWebHelper(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
private SecurityProtocolType GetSecurityProtocol()
{
int result = 0;
foreach (var value in Enum.GetValues(typeof(SecurityProtocolType)))
{
result += (int)value;
}//end foreach
return (SecurityProtocolType)result;
}
//content_type為"application/json"的情況
public T PostWebApi<T>(string url, object objPostBody)
{
//建立 HttpClient
HttpClient client = _clientFactory.CreateClient();
//忽略TLS憑證驗證(視需求
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//支持TLS連線(視需求
ServicePointManager.SecurityProtocol = this.GetSecurityProtocol();
// 指定 authorization header(若有需要的話)
//client.DefaultRequestHeaders.Add("authorization", "token {api token}");
// 要Post給WebAPI,傳遞的內容
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(objPostBody), Encoding.UTF8, "application/json");
// 發出 http post 並取得結果
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
// 回應結果字串
string strResponse = response.Content.ReadAsStringAsync().Result;
//字串反序列化為物件
var result = JsonConvert.DeserializeObject<T>(strResponse);
if (result==null)
{//為了消除VS IDE的null警告...
result = Activator.CreateInstance<T>();
}
return result;
}
}
}
我用的是.NET 7,在Program.cs加入服務↓
var builder = WebApplication.CreateBuilder(args);
//↓ Add Service
//MyWebHelper可透過DI使用HttpClient
builder.Services.AddHttpClient();
//MyWebHelper類別可以DI給Controller使用(生命週期同為應用程式)
builder.Services.AddSingleton<MyWebHelper>();
在Controller裡的使用方式↓
/// <summary>
/// 讀取組態用
/// </summary>
private readonly IConfiguration _config;
private readonly MyWebHelper _MyWebHelper;
#region 建構子
public YourController(IConfiguration config, MyWebHelper myWebHelper)
{
this._config = config;
this._MyWebHelper = myWebHelper;
}
#endregion
[HttpPost]
public IActionResult YourAction(YourClassParam param)
{
//從組態檔取得WebAPI網址
string url = this._config.GetValue<string>("yourWebAPIUrl") ?? "";
//http post給另一系統的WebAPI參數為匿名物件
var postData = new
{
yourProperty1 = "yourValue1",
yourProperty2 = "yourValue2"
};
//呼叫WebAPI
var objResult = this._MyWebHelper.PostWebApi<YourClassResult>(url, postData);
//回傳結果
return Content(JsonConvert.SerializeObject(objResult, Formatting.Indented), "application/json", Encoding.UTF8);
}
↓ ASP.NET Framework 4.5+以上 (WebForm 或 ASP.NET MVC )
先自訂義一個自用的Helper類別
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using Newtonsoft.Json;//須先透過Nuget加入此參考
namespace YourSystem.Helper
{
public class MyWebHelper
{
/// <summary>
/// content_type 若為"application/x-www-form-urlencoded" 的話,須針對值做Url編碼 Uri.EscapeDataString()
/// </summary>
/// <param name="url"></param>
/// <param name="post_content"></param>
/// <param name="content_type"></param>
/// <returns></returns>
public static string PostWebAPI(string url, string post_content, string content_type = "application/json")
{
HttpClient client = new HttpClient();
//忽略TLS憑證驗證(視需求
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//支持TLS連線(視需求
ServicePointManager.SecurityProtocol = GetSecurityProtocol();
// 指定 authorization header(若有需要的話)
//client.DefaultRequestHeaders.Add("authorization", "token {api token}");
// 要 Post傳遞給 WebAPI 的內容
StringContent content = new StringContent(post_content , Encoding.UTF8, content_type);
// 發出 http post (json body) 並取得結果
HttpResponseMessage response = client.PostAsync(url, content).Result;
// 回應結果字串
string strResponse = response.Content.ReadAsStringAsync().Result;
client.Dispose();
return strResponse;
}
private static SecurityProtocolType GetSecurityProtocol()
{
int result = 0;
foreach (var value in Enum.GetValues(typeof(SecurityProtocolType)))
{
result += (int)value;
}//end foreach
return (SecurityProtocolType)result;
}
}
}
↓ 在WebForm.cs 或 ASP.NET MVC的Controller裡的用法
//要傳遞給WebAPI的參數(匿名物件
var postData =
new
{
yourProperty1 = "yourValue1",
yourProperty2 = "yourValue2"
};
//呼叫WebApi
string strJson = MyWebHelper.PostWebApi("yourWebAPIUrl", JsonConvert.SerializeObject(postData));