c#-WebApi返回自定義狀態碼對象

 1.創建返回對象

    /// <summary>
    /// 回執對象
    /// </summary>
    public class ResultMsg
    {
        public int ResultCode { get; set; }//狀態碼
        public string ResultMessage { get; set; }//提示消息
        public object data { get; set; }//返回數據
        
        public ResultMsg SetResultMsg(int code, string msg, object datas)
        {
            ResultCode = code;
            ResultMessage = msg;
            data = datas;
            return this;
        }
    }

2.創建狀態碼枚舉

    /// <summary>
    /// 狀態碼
    /// </summary>
    public enum ResultCode
    {
        [Description("成功")]
        SUCCESS = 200,

        [Description("失敗")]
        FAIL = 400,

        [Description("請求不合理,服務器拒絕執行")]
        UNAUTHORIZED = 403,

        [Description("找不到所需數據")]
        NOT_FOUND = 404,

        [Description("服務器內部錯誤")]
        INTERNAL_SERVER_ERROR = 500
    }

3.創建獲取枚舉Descripion的方法

        /// <summary>
        /// 獲取枚舉的描述信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this object value)
        {
            if (value == null)
                return string.Empty;

            Type type = value.GetType();
            var fieldInfo = type.GetField(Enum.GetName(type, value));
            if (fieldInfo != null)
            {
                if (Attribute.IsDefined(fieldInfo, typeof(DescriptionAttribute)))
                {
                    var description =
                        Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;

                    if (description != null)
                        return description.Description;
                }
            }
            return string.Empty;
        }

4.使用方法

public ResultMsg Fun()
{
    ResultMsg resultMsg = new ResultMsg();
    resultMsg = resultMsg.SetResultMsg(
                (int)ResultCode.SUCCESS,//狀態碼200
                Fun_Helper.GetDescription(ResultCode.SUCCESS), //狀態碼消息“成功”
                data);//你要返回的數據object
    return resultMsg;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章