Mở rộng @ VisualBean của câu trả lời
On phương pháp API của điều khiển bạn có thể sử dụng mã dưới đây để thiết lập một thuộc tính như:
[SwaggerResponseContentType(responseType:"application/pdf", Exclusive=true)]
public HttpResponseMessage GetAuthorityForm(string id)
{
....
Lưu ý: 'Độc quyền = true' sẽ loại bỏ tất cả các loại nội dung khác, nếu không, sử dụng Thuộc tính mới sẽ thêm Loại nội dung phản hồi mới trong menu thả xuống Giao diện người dùng chuyển đổi. Nó sẽ KHÔNG sửa đổi Bộ điều khiển hoặc API của bạn chỉ là tài liệu.
SwaggerConfig.cs
GlobalConfiguration.Configuration
.EnableSwagger(c =>
// Set filter to apply Custom Content Types to operations
//
c.OperationFilter<ResponseContentTypeOperationFilter>();
SwaggerReponseContentTypeAttribute.cs
/// <summary>
/// SwaggerResponseContentTypeAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerResponseContentTypeAttribute : Attribute
{
/// <summary>
/// SwaggerResponseContentTypeAttribute
/// </summary>
/// <param name="responseType"></param>
public SwaggerResponseContentTypeAttribute(string responseType)
{
ResponseType = responseType;
}
/// <summary>
/// Response Content Type
/// </summary>
public string ResponseType { get; private set; }
/// <summary>
/// Remove all other Response Content Types
/// </summary>
public bool Exclusive { get; set; }
}
ResponseContentTypeOperationFilter.cs
public class ResponseContentTypeOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseContentTypeAttribute>().FirstOrDefault();
if (requestAttributes != null)
{
if (requestAttributes.Exclusive)
operation.produces.Clear();
operation.produces.Add(requestAttributes.ResponseType);
}
}
}
Shashbuckle 5 nên xử lý việc này cho bạn nếu bạn đăng ký MediaTypeFormatter trong cấu hình Web Api. –
Cảm ơn. Nghe có vẻ thông minh, nhưng tôi muốn nó cho mỗi hành động/tuyến đường. –
Tôi nghĩ bạn chỉ cần thêm nó như là một trình định dạng trong webconfig của bạn - đây là toàn cầu mặc dù, không phải trên một cơ sở cho mỗi hành động. Những gì bạn có thể làm là tạo các hoạt động của riêng mìnhFilter và chỉ áp dụng nó cho các hoạt động trả về định dạng mới – VisualBean