我有一个 ASP.NET Core 8 Web API。
这是我的
Program.cs
文件:
using Newtonsoft.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
}).AddXmlSerializerFormatters();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这是
City
课程:
public class City
{
public int Id { get; set; }
}
这是我的控制器,它有一个返回 JSON 和 XML 结果的方法:
[ApiController]
[Route("api/[controller]")]
[FormatFilter]
public class SampleController : ControllerBase
{
[HttpGet("{id:long}.{format?}")]
public ActionResult<City> GetById(long id)
{
var result = CityInfo_DataStorage.InMemoryStorage
.Cities
.FirstOrDefault(x => x.Id == 1);
return Ok(result);
}
}
问题
GetById
方法仅返回 JSON,当我尝试获取 XML 时,出现此错误:
错误:响应状态为406
我尝试像这样调用
GetById
方法:
此网址有效:
https://localhost:44347/api/Sample/1.json
此 URL 不起作用并显示错误:
https://localhost:44347/api/Sample/1.xml
有人可以帮忙吗?
谢谢
尝试将此属性添加到您的控制器:
[Produces("application/json", "application/xml")]