網路上其實有很多 但我先貼一個我自己寫的API範例給你
另外接收端其實沒有限定WEB or WIN FORM 寫好API後 不管用哪種方式都可以使用
Controllers
#region 查詢會員資料
/// <summary>
/// 查詢會員資料
/// </summary>
/// <response code="S001">查詢成功</response>
/// <response code="E001">查無資料</response>
/// <response code="E002">不在效期內</response>
/// <response code="E003">未知錯誤</response>
/// <remarks>
/// {
/// "MemberId": "1111",
/// "MemberName": "11111",
/// }
/// </remarks>
[HttpPost("GetMember")]
public Result2<MemberData> GetMember([FromBody] Member member){
var Config = new Config();
Config.connectionString = _config.GetValue<string>("connectionString");
Result2<MemberData> result = new Result2<MemberData>();
if (String.IsNullOrEmpty(member.MemberId) && String.IsNullOrEmpty(member.MemberName))
{
result.Code = "E001";
result.Message = "查無資料";
result.Stauts = "失敗";
return result;
}
try{
using (var conn = new MySqlConnection(Config.connectionString)){
conn.Open();
using (var command = conn.CreateCommand()) {
command.CommandText = "SELECT MemberId,MemberName FROM Member WHERE 1 = 1 ";
if (!String.IsNullOrEmpty(member.MemberId)){
command.CommandText += " And memberid like @MmeberId ";
command.Parameters.AddWithValue("@MmeberId", "%" + member.MemberId);
}
if (!String.IsNullOrEmpty(member.MemberName)) {
command.CommandText += " And MemberName like @MemberName ";
command.Parameters.AddWithValue("@MemberName", "%" + member.MemberName);
}
using (var reader = command.ExecuteReader()){
if (reader.HasRows){
result.Code = "S001";
result.Message = "查詢成功";
result.Stauts = "成功";
while (reader.Read()){
result.Data.Add(new MemberData() {
MemberId = (reader.IsDBNull(reader.GetOrdinal("MemberId"))) ? "" : (string)reader["MemberId"],
MemberName = (reader.IsDBNull(reader.GetOrdinal("MemberName"))) ? "" : (string)reader["MemberName"]
});
}
return result;
}
else
{
result.Code = "E001";
result.Message = "查無資料";
result.Stauts = "失敗";
return result;
}
}
}
}
}
catch (Exception ex)
{
result.Code = "E003";
result.Message = ex.Message;
result.Stauts = "未知錯誤";
return result;
}
}
#endregion
MemberData Class
public class MemberData
{
public string MemberId { get; set; }
public string MemberName { get; set; }
}
Result2 Class
public class Result2<T>
{
public string Code { get; set; }
public string Message { get; set; }
public string Stauts { get; set; }
public List<T> Data { get; set; } = new List<T>();
}
另外如果有使用 Swagger 結果會是下圖