gpt4 book ai didi

asp.net - 限制 ASP.NET Core Controller 操作中接受的媒体类型

转载 作者:行者123 更新时间:2023-12-02 02:06:27 24 4
gpt4 key购买 nike

我有一个 ASP.NET Core 服务,可以生成 JSON 和 XML 响应。但是,我喜欢将接受的媒体类型限制为仅一项操作,因此 Swagger 只能将 application/json 列为有效的响应内容类型。如何在 ASP.Net Core 中实现这一目标?

请考虑我使用的是 ASP.NET Core (ASP.NET MVC 6),而不是 ASP.NET WebAPI。

enter image description here

更新

好的,所以我将添加答案作为同一问题的一部分。感谢@Helen,我能够添加所需的类来在 ASP.Net Core (ASP.Net MVC 6) 中实现此目的。答案基于this answer但修改为使用 ASP.NET Core 类。

第 1 步。创建自定义操作过滤器属性,以便管道对禁止的内容类型使用react:

/// <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 可以反射(reflect)限制

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);
}
}
}

第 3 步。 在 Startup.cs 中的ConfigureServices 方法中配置 Swagger UI 服务,以便它可以使用新创建的操作过滤器。

    // 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" };
}

最佳答案

您可以使用注释 Consumes 和 Produces。这些也被 Swashbuckle 捡到。就像这样:

[HttpGet]
[Consumes("application/xml")]
[Produces("application/xml")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

关于asp.net - 限制 ASP.NET Core Controller 操作中接受的媒体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51158971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com