Ответ 1
Кажется, Swashbuckle не поддерживает это из коробки, но вы можете расширить его, чтобы достичь желаемого результата, при этом все еще многократно используя большую часть инфраструктуры swagger. Это может занять некоторое время и усилия, хотя и не так много в целом, но слишком много для меня, чтобы обеспечить полное решение в этом ответе. Однако я постараюсь, по крайней мере, начать. Обратите внимание, что весь код ниже не будет очень чистым и готовым к производству.
Сначала вам нужно создать и зарегистрировать пользовательский IApiExplorer
. Это интерфейс, используемый Swashbuckle для получения описаний вашего api, и он отвечает за изучение всех контроллеров и действий для сбора необходимой информации. В основном мы расширим существующий ApiExplorer с помощью кода, чтобы изучить наши классы сообщений и построить из них описание api. Сам интерфейс прост:
public interface IApiExplorer
{
Collection<ApiDescription> ApiDescriptions { get; }
}
Класс описания Api содержит различную информацию об операции api, и это то, что используется Swashbuckle для создания страницы swagger ui. Он имеет одно проблемное свойство: ActionDescriptor
. Он представляет собой действие asp.net mvc, и у нас нет действий, нет ли у нас контроллеров. Вы можете использовать поддельную реализацию этого или имитировать поведение asp.net HttpActionDescriptor и предоставлять реальные значения. Для простоты мы пойдем с первым маршрутом:
class DummyActionDescriptor : HttpActionDescriptor {
public DummyActionDescriptor(Type messageType, Type returnType) {
this.ControllerDescriptor = new DummyControllerDescriptor() {
ControllerName = "Message Handlers"
};
this.ActionName = messageType.Name;
this.ReturnType = returnType;
}
public override Collection<HttpParameterDescriptor> GetParameters() {
// note you might provide properties of your message class and HttpParameterDescriptor here
return new Collection<HttpParameterDescriptor>();
}
public override string ActionName { get; }
public override Type ReturnType { get; }
public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken) {
// will never be called by swagger
throw new NotSupportedException();
}
}
class DummyControllerDescriptor : HttpControllerDescriptor {
public override Collection<T> GetCustomAttributes<T>() {
// note you might provide some asp.net attributes here
return new Collection<T>();
}
}
Здесь мы приводим только некоторые переопределения, которые чванство будет вызывать и сбой, если мы не предоставим для них значения.
Теперь давайте определим некоторые атрибуты для украшения классов сообщений с помощью:
class MessageAttribute : Attribute {
public string Url { get; }
public string Description { get; }
public MessageAttribute(string url, string description = null) {
Url = url;
Description = description;
}
}
class RespondsWithAttribute : Attribute {
public Type Type { get; }
public RespondsWithAttribute(Type type) {
Type = type;
}
}
И некоторые сообщения:
abstract class BaseMessage {
}
[Message("/api/commands/CreateOrder", "This command creates new order")]
[RespondsWith(typeof(CreateOrderResponse))]
class CreateOrderCommand : BaseMessage {
}
class CreateOrderResponse {
public long OrderID { get; set; }
public string Description { get; set; }
}
Теперь пользовательский ApiExplorer:
class MessageHandlerApiExplorer : IApiExplorer {
private readonly ApiExplorer _proxy;
public MessageHandlerApiExplorer() {
_proxy = new ApiExplorer(GlobalConfiguration.Configuration);
_descriptions = new Lazy<Collection<ApiDescription>>(GetDescriptions, true);
}
private readonly Lazy<Collection<ApiDescription>> _descriptions;
private Collection<ApiDescription> GetDescriptions() {
var desc = _proxy.ApiDescriptions;
foreach (var handlerDesc in ReadDescriptionsFromHandlers()) {
desc.Add(handlerDesc);
}
return desc;
}
public Collection<ApiDescription> ApiDescriptions => _descriptions.Value;
private IEnumerable<ApiDescription> ReadDescriptionsFromHandlers() {
foreach (var msg in Assembly.GetExecutingAssembly().GetTypes().Where(c => typeof(BaseMessage).IsAssignableFrom(c))) {
var urlAttr = msg.GetCustomAttribute<MessageAttribute>();
var respondsWith = msg.GetCustomAttribute<RespondsWithAttribute>();
if (urlAttr != null && respondsWith != null) {
var desc = new ApiDescription() {
HttpMethod = HttpMethod.Get, // grab it from some attribute
RelativePath = urlAttr.Url,
Documentation = urlAttr.Description,
ActionDescriptor = new DummyActionDescriptor(msg, respondsWith.Type)
};
var response = new ResponseDescription() {
DeclaredType = respondsWith.Type,
ResponseType = respondsWith.Type,
Documentation = "This is some response documentation you grabbed from some other attribute"
};
desc.GetType().GetProperty(nameof(desc.ResponseDescription)).GetSetMethod(true).Invoke(desc, new object[] {response});
yield return desc;
}
}
}
}
И, наконец, зарегистрируйте IApiExplorer (после того, как вы зарегистрировали свой материал Swagger):
GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new MessageHandlerApiExplorer());
После выполнения всего этого мы можем увидеть нашу команду пользовательского сообщения в интерфейсе swagger: