我对 ASP.NET Core 8 比较陌生,并且正在尝试向我的 Web API 添加自定义端点,但收到 400 错误。我花了一些时间在谷歌上搜索试图找出问题所在,但找不到明确的答案。这只是大型项目的概念证明,因此不一定是完美的。
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"id": [ "The value 'GetOfferByKey' is not valid."]
},
"traceId": "0HN32SVRCJJQ4:00000002"
}
这是我的控制器的一部分。不知道我错过了什么。有问题的端点位于底部。感谢您的帮助。
public class OffersController : ControllerBase
{
private readonly VDM_LoaderContext _context;
private readonly IDbContextFactory<VDM_LoaderContext> _contextFactory;
private readonly OfferService _offerService;
public OffersController(VDM_LoaderContext context, IDbContextFactory<VDM_LoaderContext> factory)
{
_contextFactory = factory;
_context = context;
}
// GET: api/Offers
[HttpGet]
public async Task<ActionResult<IEnumerable<Offer>>> GetOffers()
{
return await _context.Offers.ToListAsync();
}
// GET: api/Offers/5
[HttpGet("{id}")]
public async Task<ActionResult<Offer>> GetOffer(int id)
{
var offer = await _context.Offers.FindAsync(id);
if (offer == null)
{
return NotFound();
}
return offer;
}
/***** this is the endpoint causing problems *****/
// GET: api/Offers/GetOfferByKey/{offerKey}
[Route("api/Offers/GetOfferByKey/{offerKey}")]
public async Task<ActionResult<Offer>> GetOfferByKey(int offerKey)
{
var offer = await _contextFactory.CreateDbContext()
.Offers
.Where(o => (o.OfferKey == null ? string.Empty : o.OfferKey).Equals(offerKey))
.FirstOrDefaultAsync();
if (offer == null)
{
return NotFound();
}
return offer;
}
.
.
.
}
我尝试添加
[Route]
属性,但这没有帮助。我发现一篇文章说要确保您的 WebConfig.cs
文件启用了以下行的属性路由:
config.MapHttpAttributeRoutes();
但是,我的项目没有
WebConfig.cs
文件。我正在使用 .NET 8。
您可以通过像这样修改代码来简单地做到这一点。
[HttpGet("api/Offers/GetOfferByKey/{offerKey}")]
public async Task<ActionResult<Offer>> GetOfferByKey(int offerKey)
{
var offer = await _contextFactory.CreateDbContext()
.Offers
.FirstOrDefaultAsync(o => o.OfferKey == offerKey);
if (offer == null)
{
return NotFound();
}
return offer;
}