输出格式化程序 XmlDataContractSerializerOutputFormatter asp.net 核心未



我的.NET Core API测试项目包含应以XML格式返回的数据,因此我在Startup类中安装并设置了XmlDataContractSerializerOutputFormatter

services.AddMvc(setupAction => 
{
setupAction.ReturnHttpNotAcceptable = true;
setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); 
});

一旦我将 Postman 中的接受标头设置为application/xml值,数据就会以 XML 形式返回,但这只能到达父级和第一个子项,之后,结果是标准的 JSON 格式。 有孙子的父母

有第一个孩子的父母

作者控制器代码:

namespace Lib.Controllers
{
[Route("api/authors/{authorId}/books")]
public class BooksController : Controller
{
private ILibraryRepository _libraryRepository;
public BooksController(ILibraryRepository libraryRepository)
{
_libraryRepository = libraryRepository;
}
[HttpGet()]
public IActionResult GetBooksForAuthor(Guid authorId)
{
if (!_libraryRepository.AuthorExists(authorId))
{
return NotFound();
}
var booksForAuthorFromRepo = _libraryRepository.GetBooksForAuthor(authorId);
var booksForAuthor = AutoMapper.Mapper.Map<IEnumerable<BookDto>>(booksForAuthorFromRepo);
return Ok(booksForAuthor);
}

[HttpGet("{id}")]
public IActionResult GetBookForAuthor(Guid authorId, Guid Id)
{
if (!_libraryRepository.AuthorExists(authorId))
{
return NotFound();
}
var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, Id);
if (bookForAuthorFromRepo == null)
{
return NotFound("The book does not exist");
}
var bookForAuthor = AutoMapper.Mapper.Map<BookDto>(bookForAuthorFromRepo);
return new JsonResult(bookForAuthor);
}
}
}

书籍控制器代码:

namespace Lib.Controllers
{
[Route("api/authors/{authorId}/books")]
public class BooksController : Controller
{
private ILibraryRepository _libraryRepository;
public BooksController(ILibraryRepository libraryRepository)
{
_libraryRepository = libraryRepository;
}
[HttpGet()]
public IActionResult GetBooksForAuthor(Guid authorId)
{
if (!_libraryRepository.AuthorExists(authorId))
{
return NotFound();
}
var booksForAuthorFromRepo = _libraryRepository.GetBooksForAuthor(authorId);
var booksForAuthor = AutoMapper.Mapper.Map<IEnumerable<BookDto>>(booksForAuthorFromRepo);
return Ok(booksForAuthor);
}

[HttpGet("{id}")]
public IActionResult GetBookForAuthor(Guid authorId, Guid Id)
{
if (!_libraryRepository.AuthorExists(authorId))
{
return NotFound();
}
var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, Id);
if (bookForAuthorFromRepo == null)
{
return NotFound("The book does not exist");
}
var bookForAuthor = AutoMapper.Mapper.Map<BookDto>(bookForAuthorFromRepo);
return new JsonResult(bookForAuthor);
}
}
}

将返回类型从 JsonResult(( 更改为 Ok(( 解决了这个问题。 感谢@PanagiotisKanavos

最新更新