我有一个生成JSON和XML响应的ASP.NET Core服务。然而,我想限制只有一个操作接受媒体类型,以便Swagger只能将application/json列为有效的响应内容类型。我如何在ASP.Net Core中实现这一点?
请考虑我正在使用ASP.Net Core(ASP.NET MVC 6),而不是ASP.NET WebAPI。
更新
好的,所以我会将答案添加到同一个问题中。多亏了@Helen,我能够添加所需的类来在ASP.Net Core(ASP.Net MVC 6)中实现这一点。答案基于此答案,但修改为使用ASP.NET Core类。
步骤1。 创建自定义操作过滤器属性,以便管道对禁止的内容类型做出反应:
/// <summary>
/// SwaggerResponseContentTypeAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerResponseContentTypeAttribute : ActionFilterAttribute
{
/// <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; }
public override void OnActionExecuting(ActionExecutingContext context)
{
var accept = context.HttpContext.Request.Headers["accept"];
var accepted = accept.ToString().ToLower().Contains(ResponseType.ToLower());
if (!accepted)
context.Result = new StatusCodeResult((int)HttpStatusCode.NotAcceptable);
}
}
步骤 2。创建一个 Swagger 操作过滤器,以便 UI 反映出限制。
public class ResponseContentTypeOperationFilter : IOperationFilter
{
public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context)
{
var requestAttributes = context.ControllerActionDescriptor.GetControllerAndActionAttributes(true).Where(c=>c.GetType().IsAssignableFrom(typeof(SwaggerResponseContentTypeAttribute))).Select(c=> c as SwaggerResponseContentTypeAttribute).FirstOrDefault();
if (requestAttributes != null)
{
if (requestAttributes.Exclusive)
operation.Produces.Clear();
operation.Produces.Add(requestAttributes.ResponseType);
}
}
}
第三步。 在Startup.cs文件的ConfigureServices方法中配置Swagger UI服务,以便它可以使用新创建的Operation Filter。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.OperationFilter<ResponseContentTypeOperationFilter>();
});
}
步骤4。给这个动作做注释
// GET api/values
[HttpGet]
[WebService.Utils.SwaggerResponseContentType(responseType: "application/json", Exclusive = true)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
options.OutputFormatters.RemoveType<XmlDataContractSerializerOutputFormatter>()
是什么意思? - Mark G