Reputation: 4728
I want to add an Action to my Invoices
controller which has a DateTime
parameter:
Here is my Controller with my action:
[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);
}
}
}
I had in the startup.cs
file this line:
// 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" }));
}
What's wrong in my code ? Thank you
UPDATE
I would like an URL this: format http://domain/api/invoices/filterby/2017-01-01
Upvotes: 2
Views: 6062
Reputation: 926
hm.. I think it is not typical route and parameter with ASP.NET WebAPI, I am also not sure it's WebSite or WebAPI.
It works for me (url format like: 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);
}
}
}
--
In my opinion, I would like to make it simple: only use route attribute with WebAPI.
only use app.UseMvc(); in Startup.cs
add route attribute in controller:
Finally, make sure your WebAPI url with parameter(HTTP GET)
http://localhost:xxxx/api/Invoices/FilterBy?date=2017-01-01
Upvotes: 3