[英]How to add an Action with a DateTime parameter?
我想向我的Invoices
控制器添加一個 Action,它有一個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" }));
}
我的代碼有什么問題? 謝謝
更新
我想要一個 URL:格式http://domain/api/invoices/filterby/2017-01-01
嗯..我認為這不是 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 的路由屬性。
只使用 app.UseMvc(); 在 Startup.cs
最后,確保您的 WebAPI url 帶有參數(HTTP GET)
http://localhost:xxxx/api/Invoices/FilterBy?date=2017-01-01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.