【发布时间】:2019-05-25 11:22:01
【问题描述】:
我在大摇大摆地将我的 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);
}
结果:
此时:
[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;
}
结果:
由于为不同的参数返回不同的数据结构,我无法返回已解析对象的列表。所以此时我只收到原始肥皂 xml-data 并且必须对其进行解析/反序列化。但为了真正能够看到原始响应,我还需要将其显示为内容类型为 application/xml 的字符串中的内容。它给了我一个很好的输出,比如(尽管它仍然说只有 application/json 是可能的):
总结一下:
当字符串被解析为如下所示的实际格式时,我没有让它与显示正确内容类型的响应内容类型一起工作(在“响应内容类型”-过滤器中)。即使这会导致最重要的应用程序/xml 的正确输出(参见上面的屏幕截图);
[Produces("application/json", "application/xml")]
public ContentResult GetByAddress(string address)
{
return Content("<xml>...</xml>", "application/xml", Encoding.UTF8);
}
【问题讨论】:
-
能否也包含
services.AddSwaggerGen配置的部分?
标签: c# asp.net-core swagger