.NetCore Web Api 利用ActionFilterAttribute統一接口返回值格式及問題解析

.Net Core 同 Asp.Net MVC一樣有幾種過濾器,這裡不再贅述每個過濾器的執行順序與作用。

在實際項目開發過程中,統一API返回值格式對前端或第三方調用將是非常必要的,在.NetCore中我們可以通過ActionFilterAttribute來進行統一返回值的封裝。

在封裝之前我們需要考慮下面幾個問題:

1,需要對哪些結果進行封裝

我目前的做法是,隻對ObjectResult進行封裝,其他的類型:FileResult,ContentResult,EmptyResult,RedirectResult不予處理

2,對異常錯誤的封裝

既然是統一返回值,當然也要考慮接口異常的問題瞭

但是不是所有的異常我們都需要返回給前端的,我們可能需要自定義一個業務異常,業務異常可以在前端進行友好提示,系統異常完全沒必要拋出給前端或第三方,且需要對系統異常進行日志記錄

項目結構:

Exceptions:自定義業務異常

Filters:自定義過濾器(統一結果封裝,全局異常)

Models:統一結果實體

部分代碼:

using System;
 
namespace NetCoreCommonResult.Exceptions
{
    /// <summary>
    /// 自定義業務異常,可以由前端拋出友好的提示
    /// </summary>
    public class BizException:Exception
    {
        public BizException()
        {
        }
        public BizException(string message):base(message)
        public BizException(string message, Exception ex) : base(message, ex)
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
 
namespace NetCoreCommonResult.Filters
{
    public class CommonResultFilterAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ObjectResult objRst)
            {
                if (objRst.Value is Models.ApiResult)
                    return;
                context.Result = new ObjectResult(new Models.ApiResult
                {
                    Success = true,
                    Message = string.Empty,
                    Data = objRst.Value
                });
            }
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
 
namespace NetCoreCommonResult.Filters
{
    public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger<GlobalExceptionFilterAttribute> _logger;
        public GlobalExceptionFilterAttribute(ILogger<GlobalExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }
        public override void OnException(ExceptionContext context)
        {
            context.ExceptionHandled = true;
            var isBizExp = context.Exception is Exceptions.BizException;
            context.Result = new ObjectResult(new Models.ApiResult
            {
                Success = false,
                Message = context.Exception.Message
            });
            //非業務異常記錄errorLog,返回500狀態碼,前端通過捕獲500狀態碼進行友好提示
            if (isBizExp == false)
            {
                _logger.LogError(context.Exception, context.Exception.Message);
                context.HttpContext.Response.StatusCode = 500;
            }
            base.OnException(context);
        }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
 
namespace NetCoreCommonResult
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
            services.AddLogging();
            services.AddControllers(ops =>
            {
                //添加過濾器
                ops.Filters.Add(new Filters.CommonResultFilterAttribute());
                //GlobalExceptionFilterAttribute構造中註入其他服務,需要通過ServiceFilter添加
                ops.Filters.Add(new Microsoft.AspNetCore.Mvc.ServiceFilterAttribute(typeof(Filters.GlobalExceptionFilterAttribute)));
            });
            //註冊GlobalExceptionFilterAttribute
            services.AddScoped<Filters.GlobalExceptionFilterAttribute>();
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            }
            else
                app.UseExceptionHandler("/Error");
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
                endpoints.MapControllers();
    }
}

最後新建一個Controller然後寫上幾個不同返回值的的Action

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
 
namespace NetCoreCommonResult.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        /// <summary>
        /// string
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Index() => "Welecome to .NetCore";
        /// 跳轉,不處理
        [HttpGet("redirect")]
        public ActionResult Redirect() => RedirectToAction("Index");
        ///
        [HttpGet("num")]
        public int Num() => 10;
        /// 異步
        [HttpGet("async")]
        public Task<IEnumerable<string>> TaskString() =>Task.FromResult<IEnumerable<string>>(new[] { "A","B","C"});
        /// 文件輸出,不處理
        [HttpGet("file")]
        public ActionResult GetFile() => File(Encoding.UTF8.GetBytes("File String"), "text/plain");
        /// 空返回值,不處理
        [HttpGet("empty")]
        public ActionResult Empty() => Empty();
        /// contentResult 不處理
        [HttpGet("content")]
        public ActionResult Content() => Content("this is content");
        /// 異常,返回500錯誤
        [HttpGet("exception")]
        public ActionResult GetException() => throw new InvalidOperationException("invalid");
        /// 自定義異常,返回200
        [HttpGet("bizException")]
        public ActionResult GetBizException() => throw new Exceptions.BizException("bizException");
    }
}

下面是返回結果截圖:

上圖:訪問/api/home和/api/home/redirect的結果

上圖:Action返回數字的結果

上圖:返回string集合的結果

上圖:輸出文本文件的結果

上圖:返回ContentResult的結果

上圖:系統異常的結果,輸出狀態碼為500

上圖:拋出業務異常的結果,輸出狀態碼200

不知道如何上傳ZIP包,實例代碼項目已經放到Gitee上瞭,後面有時間也會寫點簡單的例子
地址:https://gitee.com/tang3402/net-core-samples.git

到此這篇關於.NetCore Web Api 利用ActionFilterAttribute統一接口返回值格式的文章就介紹到這瞭,更多相關.NetCore Web Api 統一接口返回值格式內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: