如何使用DateTime参数添加Action?

时间:2018-02-12 19:05:34

标签: asp.net-core routing asp.net-mvc-routing

我想在我的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

1 个答案:

答案 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属性。

仅使用app.UseMvc();在Startup.cs enter image description here

在contorller中添加路由属性: enter image description here

最后,确保您的WebAPI网址带参数(HTTP GET)

  

http://localhost:xxxx/api/Invoices/FilterBy?date=2017-01-01

enter image description here