WEB API
最近在寫專案稍微記錄一下定義泛型的API的物件,下次懶得再回想,直接呼叫調用,順便有跟同事講這一塊自己是怎麼使用列舉說明和定義API的物件
以.Net Core Web Api為例,建立新專案,這些步驟直接略過了,定義以下要回傳的狀態以及列舉說明擴充方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.ViewModel
{
public enum ResponseCode
{
[Description("成功")]
Success = 200,
[Description("查無此資料")]
NotFound = 404,
}
public class ResponseVM<T>
{
/// <summary>
/// 執行成功與否
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 狀態碼
/// </summary>
public ResponseCode ResponseCode { get; set; }
/// <summary>
/// 錯誤訊息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 資料本體
/// </summary>
public T Data { get; set; }
public ResponseVM<T> Success()
{
ResponseCode = ResponseCode.Success;
IsSuccess = true;
Message = ResponseCode.Success.GetEnumDescription();
return this;
}
public ResponseVM<T> Success(T data)
{
ResponseCode = ResponseCode.Success;
IsSuccess = true;
Data = data;
Message = ResponseCode.Success.GetEnumDescription();
return this;
}
public ResponseVM<T> Fail(ResponseCode responseCode)
{
ResponseCode = responseCode;
IsSuccess = false;
Message = responseCode.GetEnumDescription();
return this;
}
}
}
上述定義了列舉狀態之後,再回頭定義擴充方法,定義取說明
namespace WebApplication1
{
public static class MyExtensions
{
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
//若取不到屬性,則取名稱
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
}
}
定義一個回傳的Customer資料物件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.ViewModel
{
public class ReponseCustomerVM
{
public string CustomerId { get; set; }
public string CustomerName { get; set; }
}
}
API端部分塞假資料,若是回傳成功把撈取資料的塞在Success物件裡面。
[HttpGet]
[Route("Customer/All")]
public ResponseVM<List<ReponseCustomerVM>> GetCustomers()
{
var responseCustomers = new List<ReponseCustomerVM>();
responseCustomers.Add(new ReponseCustomerVM
{
CustomerId = "001",
CustomerName = "AA"
});
responseCustomers.Add(new ReponseCustomerVM
{
CustomerId = "002",
CustomerName = "BB"
});
return new ResponseVM<List<ReponseCustomerVM>>()
.Success(responseCustomers);
}
元哥的筆記