在ASP.Net Core Web API中,建议避免返回匿名类型的对象。这是因为匿名类型是根据属性的名称和值来生成类型的,这意味着每次调用该方法时,都会生成一个不同的类型。这会使类型不稳定,难以使用Swagger文档以及许多其他问题。
因此,我们可以使用DTO(数据传输对象)来保持返回类型的稳定性。在DTO中,我们定义了要返回的属性以及其类型,并在操作中使用该DTO作为返回类型。以下是一个示例DTO和控制器操作的代码:
DTO示例:
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
}
控制器操作示例:
[HttpGet("[action]")]
public IActionResult GetProduct(int id)
{
var product = _context.Products.Find(id);
if (product == null)
{
return NotFound();
}
var productDTO = new ProductDTO
{
Id = product.Id,
Name = product.Name,
Price = product.Price,
Description = product.Description
};
return Ok(productDTO);
}
从上面的代码中,我们可以看到,通过使用DTO,我们可以将返回类型保持稳定,并返回我们需要的属性,而不是使用匿名类型。