ASP.NET Core WebApiは、統合フォーマットパラメータを返します.

1936 ワード

ビジネスシーン:
ビジネス要件は、WebApiインタフェースサービスに対してパラメータを統一的に返す必要があります.つまり、実際の結果を一定のフォーマットで包む必要があります.例えば、次のフォーマットです.
{
    "response":{
        "code":200,
        "msg":"Remote service error",
        "result":""
    }
}

具体的な実装:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class WebApiResultMiddleware : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        //            
        if (context.Result is ObjectResult)
        {
            var objectResult = context.Result as ObjectResult;
            if (objectResult.Value == null)
            {
                context.Result = new ObjectResult(new { code = 404, sub_msg = "     ", msg = "" });
            }
            else
            {
                context.Result = new ObjectResult(new { code = 200, msg = "", result = objectResult.Value });
            }
        }
        else if (context.Result is EmptyResult)
        {
            context.Result = new ObjectResult(new { code = 404, sub_msg = "     ", msg = "" });
        }
        else if (context.Result is ContentResult)
        {
            context.Result = new ObjectResult(new { code = 200, msg = "", result= (context.Result as ContentResult).Content });
        }
        else if (context.Result is StatusCodeResult)
        {
            context.Result = new ObjectResult(new { code = (context.Result as StatusCodeResult).StatusCode, sub_msg = "", msg = "" });
        }
    }
}
Startup対応する構成を追加します.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(WebApiResultMiddleware));
        options.RespectBrowserAcceptHeader = true;
    });
}