[HttpPost] [Produces("application/json")] public IActionResult MyAction() { // code here return Ok(myObject); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddXmlSerializerFormatters() .AddJsonOptions(options => { options.SerializerSettings.Formatting = Formatting.Indented; }); }
如果以上方法都没有解决问题,可以使用中间件来控制响应格式。例如:
public class ResponseFormatMiddleware { private readonly RequestDelegate _next;
public ResponseFormatMiddleware(RequestDelegate next) { _next = next; }
public async Task Invoke(HttpContext context) { // 进行格式控制 // ... await _next(context); } }
在Startup中注册中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware