亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Net Core API:將 ProducesResponseType 設置為全局參數或自動化

Net Core API:將 ProducesResponseType 設置為全局參數或自動化

C#
慕運維8079593 2023-12-17 20:03:46
我們有 100 多個 API,并且必須為我們所有的 API 在頂部、200 個、500 個等編寫 ProducesResponseType。有沒有一種方法可以為我們所有的 get 函數制作這個全局參數,這樣我們就不必繼續重復代碼?嘗試讓API遵循Dry原則,成為瘦控制器。[HttpGet("[Action]/{id}")][ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status200OK)][ProducesResponseType(StatusCodes.Status404NotFound)][ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status500InternalServerError)]public async Task<ActionResult<GetBookResponse>> GetByBook(int id){   var book = await bookservice.GetBookById(id);   return Ok(book);}
查看完整描述

2 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

您可以創建自定義IApplicationModelProvider并在OnProvidersExecuting方法中添加所需的過濾器。


ProduceResponseTypeModelProvider.cs


public class ProduceResponseTypeModelProvider : IApplicationModelProvider

{

    public int Order => 3;


    public void OnProvidersExecuted(ApplicationModelProviderContext context)

    {

    }


    public void OnProvidersExecuting(ApplicationModelProviderContext context)

    {

        foreach (ControllerModel controller in context.Result.Controllers)

        {

            foreach (ActionModel action in controller.Actions)

            {

                // I assume that all you actions type are Task<ActionResult<ReturnType>>


                Type returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];


                action.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status510NotExtended));

                action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status200OK));

                action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status500InternalServerError));

            }

        }

    }

}

然后你需要將其注冊到IServiceCollection


啟動.cs


public void ConfigureServices(IServiceCollection services)

{

    ...   

    services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, ProduceResponseTypeModelProvider>());

    ...

}


查看完整回答
反對 回復 2023-12-17
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

我們也使用這行代碼, 它提供錯誤處理、動詞屬性檢查以及參數是否存在,


public class ProduceResponseTypeModelProvider : IApplicationModelProvider

? ? {

? ? ? ? public int Order => 3;


? ? ? ? public void OnProvidersExecuted(ApplicationModelProviderContext context)

? ? ? ? {

? ? ? ? }


? ? ? ? public void OnProvidersExecuting(ApplicationModelProviderContext context)

? ? ? ? {

? ? ? ? ? ? foreach (ControllerModel controller in context.Result.Controllers)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? foreach (ActionModel action in controller.Actions)

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? Type returnType = null;

? ? ? ? ? ? ? ? ? ? if (action.ActionMethod.ReturnType.GenericTypeArguments.Any())

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? if (action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments().Any())

? ? ? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? ? ? returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];

? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? }


? ? ? ? ? ? ? ? ? ? var methodVerbs = action.Attributes.OfType<HttpMethodAttribute>().SelectMany(x => x.HttpMethods).Distinct();

? ? ? ? ? ? ? ? ? ? bool actionParametersExist = action.Parameters.Any();


? ? ? ? ? ? ? ? ? ? AddUniversalStatusCodes(action, returnType);


? ? ? ? ? ? ? ? ? ? if (actionParametersExist == true)

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? AddProducesResponseTypeAttribute(action, null, 404);

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? if (methodVerbs.Contains("POST"))

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? AddPostStatusCodes(action, returnType, actionParametersExist);

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }


? ? ? ? public void AddProducesResponseTypeAttribute(ActionModel action, Type returnType, int statusCodeResult)

? ? ? ? {

? ? ? ? ? ? if (returnType != null)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? action.Filters.Add(new ProducesResponseTypeAttribute(returnType, statusCodeResult));

? ? ? ? ? ? }

? ? ? ? ? ? else if (returnType == null)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? action.Filters.Add(new ProducesResponseTypeAttribute(statusCodeResult));

? ? ? ? ? ? }

? ? ? ? }


? ? ? ? public void AddUniversalStatusCodes(ActionModel action, Type returnType)

? ? ? ? {

? ? ? ? ? ? AddProducesResponseTypeAttribute(action, returnType, 200);

? ? ? ? ? ? AddProducesResponseTypeAttribute(action, null, 500);

? ? ? ? }


? ? ? ? public void AddPostStatusCodes(ActionModel action, Type returnType, bool actionParametersExist)

? ? ? ? {

? ? ? ? ? ? AddProducesResponseTypeAttribute(action, returnType, 201);

? ? ? ? ? ? AddProducesResponseTypeAttribute(action, returnType, 400);

? ? ? ? ? ? if (actionParametersExist == false)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? AddProducesResponseTypeAttribute(action, null, 404);

? ? ? ? ? ? }

? ? ? ? }

? ? }


查看完整回答
反對 回復 2023-12-17
  • 2 回答
  • 0 關注
  • 407 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號