早上好
我有困难设置我的HTTPGETs,然后在邮差测试解决方案。
我试图在这两种情况下返回一个结果,但是当我输入参数时没有加载。所以我显然遗漏了一些东西,我需要一些帮助。
我有一个参数{id}在我的CashMovementController,如果我导航到localhost/api/cashmovements/{id}它加载,但如果传递{id}参数在邮差失败。
然后在我的BondCreditRatingsController我有2个参数{ISIN} &{日期},我不确定如何处理这个
希望听到一些建议/帮助在这方面,请
谢谢取而代之
Startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CashMovementsController.cs
[Route("api/[controller]")]
public class CashMovementsController : Controller
{
private ICashMovementRepository _cashmovementRepository;
[HttpGet("{id}", Name = "GetCashMovement")]
public IActionResult Get(int id)
{
CashMovement _cashmovement = _cashmovementRepository.GetSingle(u => u.CashMovementId == id);
if (_cashmovement != null)
{
CashMovementViewModel _cashmovementVM = Mapper.Map<CashMovement, CashMovementViewModel>(_cashmovement);
return new OkObjectResult(_cashmovementVM);
}
else
{
return NotFound();
}
}
}
BondCreditRatingsController.cs
[Route("api/[controller]")]
public class BondCreditRatingsController : Controller
{
private IBondCreditRatingRepository _bondcreditratingRepository;
public BondCreditRatingsController(IBondCreditRatingRepository bondcreditratingRepository)
{
_bondcreditratingRepository = bondcreditratingRepository;
}
[HttpGet("{id}", Name = "GetBondCreditRating")]
public IActionResult Get(string id, DateTime efffectivedate)
{
BondCreditRating _bondcreditrating = _bondcreditratingRepository.GetSingle(u => u.ISIN == id, u => u.EffectiveDate == efffectivedate);
if (_bondcreditrating != null)
{
BondCreditRatingViewModel _bondcreditratingVM = Mapper.Map<BondCreditRating, BondCreditRatingViewModel>(_bondcreditrating);
return new OkObjectResult(_bondcreditratingVM);
}
else
{
return NotFound();
}
}
如果你想将它映射到api/Controller/method/id,你需要使用下面的代码,因为你想将参数顺序(没有其他标识符)映射到动作中的特定参数名称。
[HttpGet("GetCashMovement/{id}")]
由于你使用的是命名参数,并且请求不能映射到任何其他模板,所以你当前的代码应该使用下面的代码。
/api/CashMovements/GetCashMovement?id=1
但是这个属性语法也会(可能是无意的)触发:
/api/CashMovements/1
因为该动作的定义模板的总和是:
[Route("api/[controller]/{id}")]
/api/ApiTest/GetCashMovement映射GetCashMovement的原因Get(int i)是因为id在startup
中定义为可选的routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/**{id?}**");
路由参数名后面的问号定义了一个可选参数。
https://learn.microsoft.com/en us/aspnet/core/fundamentals/routing?view=aspnetcore - 3.0 # create-routes