Falcon.SugarApi/Falcon.SugarApi/ApiDefinistions/ApiResponseTypeModelProvider.cs

56 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Falcon.SugarApi.ApiDefinistions
{
/// <summary>
/// api接口返回值模型定义
/// </summary>
public class ApiResponseTypeModelProvider : IApplicationModelProvider
{
/// <inheritdoc/>
public int Order => 1;
/// <inheritdoc/>
public void OnProvidersExecuted(ApplicationModelProviderContext context) {
}
/// <inheritdoc/>
public void OnProvidersExecuting(ApplicationModelProviderContext context) {
foreach (ControllerModel controller in context.Result.Controllers) {
foreach (ActionModel action in controller.Actions) {
if (!isApiAction(action)) {
continue;
}
var art = action.ActionMethod.ReturnType;
Type returnType =
art.IsGenericType && art.IsAssignableFrom(typeof(Task<>)) ? art.GenericTypeArguments[0].GetGenericArguments()[0] :
art;
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status200OK));
action.Filters.Add(new ProducesResponseTypeAttribute(typeof(ExceptionModel), StatusCodes.Status400BadRequest));
}
}
}
/// <summary>
/// 方法是否为api方法
/// </summary>
/// <param name="am">Action模型</param>
/// <returns>是api方法返回true否则false</returns>
protected static bool isApiAction(ActionModel am) {
if (am.Controller.Attributes.Any(c => c is ApiControllerAttribute)) {
return true;
}
if (am.Attributes.Any(c => c is ApiControllerAttribute)) {
return true;
}
return false;
}
}
}