.NET MVC API返回JSON對象


方法多種,自己目前采用的是自定義返回格式的方法,不需要修改配置文件。

輔助類:

 1 public class ApiResponseHelper
 2     {
 3         public static HttpResponseMessage ToJson(Object obj)
 4         {
 5             String str;
 6             if (obj is String || obj is Char)
 7             {
 8                 str = obj.ToString();
 9             }
10             else
11             {
12                 JavaScriptSerializer serializer = new JavaScriptSerializer();
13                 str = serializer.Serialize(obj);
14             }
15             HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
16             return result;
17         }
18     }

調用:

[LoginFilter(IsCheck = false)]
        [HttpGet]
        public object Audit(int id, int status)
        {
            try
            {
                auditSvc.BulkUpdateByQuery(c => c.ID == id, d => new HXAudit { AuditStatus = status, AuditTime = DateTime.Now });
                return ApiResponseHelper.ToJson(new { status = true, message = "成功", data = new { } });
            }
            catch (Exception e)
            {
                return ApiResponseHelper.ToJson(new { status = false, message = e.Message, data = new { } });
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM