swagger、.net core API中的响应内容类型

jw5wzhpr  于 12个月前  发布在  .NET
关注(0)|答案(4)|浏览(143)

我在swagger中将我的API响应呈现为xml时遇到了一些问题,最后我用下面的第一个操作将它呈现为正确的格式application/xml,但它仍然说我只能将它呈现为application/json。
我尝试从Produces属性中删除application/json,但仍然只显示application/json。
你知道它为什么会这样吗?

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()));
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = "";
    });
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey" });
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
            { "Bearer", Enumerable.Empty<string>() },
        });
    });
}

字符串
行动:

[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}


结果相同:

[Produces("application/json", "application/xml")]
public IActionResult GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return Content(result, "application/xml", Encoding.UTF8);
}


结果:
x1c 0d1x当单击执行时,我得到了正确的XML格式的结果。
而这:

[Produces("application/json", "application/xml")]
public string GetByAddress(string address)
{
    var addressId = GetAddressIdByAddress(address);
    string result = _soapApi.GetResultById(addressId);
    return result;
}


或者这个:

[Produces("application/json", "application/xml")]
public List<Address> GetByAddreses()
{
    string result = _soapApi.GetResults();
    return result;
}


结果:



由于不同参数返回的数据结构不同,我无法返回解析对象的列表。因此,此时我只接收原始soap xml数据,并必须解析/解析它。但为了实际能够看到原始响应,我还需要将其显示为Content from string with content-type application/xml。它给了我一个很好的输出,如(尽管它仍然说只有application/json是可能的):



总结一下:
当一个字符串被解析成它的实际格式时,我没有让它在响应内容类型中显示正确的内容类型(在“响应内容类型”-过滤器中)。即使这导致了最重要的application/xml的正确输出(见上面的截图);

[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
    return Content("<xml>...</xml>", "application/xml", Encoding.UTF8);
}

3duebb1j

3duebb1j1#

这是因为返回类型覆盖了注解。为了让它像你希望的那样工作,你需要返回IconstructResult并使用注解来提供特定代码的响应类型模型。
因此,返回Ok(result),而不是返回result
我创建了示例代码,使用swagger4.0.1可以运行

[HttpGet("Get2")]
[Produces("application/json", "application/xml", Type = typeof(List<string>))]
public IActionResult Get2()
{
   var list = new List<string>() { "value1", "value2" };
   return Ok(list);
}

字符串


的数据

5jdjgkvh

5jdjgkvh2#

[Produces("application/json", "application/xml")]
public Task<IActionResult> GetByAddreses()
{
    var result = _soapApi.GetResults();
var response = ResponceMethod<List<Address>>.SuccessResponse(StatusCodes.Status200OK, "Success", result);
    return Ok(response);
}

字符串

92vpleto

92vpleto3#

我正在测试一个用asp.net core2.2开发的web API应用程序。
我安装了Microsoft.AspNetCore.Mvc.Formatters.Xmlnuget包。
然后,我通过添加更新了Startup.cs中的ConfigureServices方法。

services.AddMvc().AddXmlSerializerFormatters();

字符串
我的web API swagger正在按照我的需要工作,并显示了JSON和XML,并得到了预期的格式。如果您需要更多信息,请访问:https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

ig9co6j1

ig9co6j14#

现在天在NET6+您可以设置他们的应用程序范围内注册

builder.Services.AddControllers(options =>
{
    //here you can control the order and types for all responses as they will appear in swagger.json
    //technically if an endpoint returns binary image it can be changed per endpoint using either [Produces] or [SwaggerResponse] attribute
    options.Filters.Add(new ProducesAttribute("application/json", "text/json", "text/plain"));
})

字符串

相关问题