(精华)2020年6月29日 C#类库 格式化返回结果

using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;

namespace Core.Api
{
    /// 
    /// 若Action返回对象为自定义对象,则将其转为JSON
    /// 
    public class FormatResponseAttribute : BaseActionFilterAsync
    {
        public override async Task OnActionExecuted(ActionExecutedContext context)
        {
            if (context.ContainsFilter<NoFormatResponseAttribute>())
                return;

            if (context.Result is EmptyResult)
                context.Result = Success();
            else if (context.Result is ObjectResult res)
            {
                if (res.Value is AjaxResult)
                    context.Result = JsonContent(res.Value.ToJson());
                else
                    context.Result = Success(res.Value);
            }

            await Task.CompletedTask;
        }
    }
}
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace Core.Api
{
    /// 
    /// 返回结果不进行格式化
    /// 
    public class NoFormatResponseAttribute : Attribute, IActionFilter
    {
        /// 
        /// Action执行之前执行
        /// 
        /// 过滤器上下文
        public void OnActionExecuting(ActionExecutingContext context)
        {

        }

        /// 
        /// Action执行完毕之后执行
        /// 
        /// 
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
    }
}

你可能感兴趣的:(#,C#类库/Filter,c#,asp.net,后端)