我想在我的Invoices
控制器中添加一个操作,该控制器具有DateTime
参数:
这是我的控制器与我的行动:
[Route("api/[controller]")]
public class InvoicesController : Controller
{
private readonly IInvoiceRepository _repository;
private readonly ILogger<InvoicesController> _logger;
public InvoicesController(IInvoiceRepository repository, ILogger<InvoicesController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet]
public IActionResult FilterBy(DateTime date)
{
try
{
return Ok(_repository.GetInvoicesByDate(date));
}
catch (Exception ex)
{
string errorMessage = "Failed to get invoices by date";
_logger.LogError("{0} {1}", errorMessage, ex);
return BadRequest(errorMessage);
}
}
}
我在startup.cs
文件中有这一行:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
routes.MapRoute(
name: "getInvoicesByDate",
template: "api/Invoices/{action}/{date:DateTime}",
defaults: new { controller = "Invoices", action = "FilterBy" }));
}
我的代码有什么问题?谢谢
更新
我想要一个网址:格式http://domain/api/invoices/filterby/2017-01-01
答案 0 :(得分:2)
HM .. 我认为它不是ASP.NET WebAPI的典型路由和参数,我也不确定它是WebSite还是WebAPI。
它适用于我(网址格式如:domain / api / invoices / filterby / 2017-01-01):
[Route("api/[controller]")]
public class InvoicesController : Controller
{
[HttpGet("[action]/{date}")]
public IActionResult FilterBy(DateTime date)
{
try
{
return Ok(date);
}
catch (Exception ex)
{
string errorMessage = "Failed to get invoices by date";
return BadRequest(errorMessage);
}
}
}
-
在我看来,我想说的很简单:只使用带有WebAPI的route属性。
中最后,确保您的WebAPI网址带参数(HTTP GET)