首页 > 解决方案 > FormatAttribute 需要正斜杠来执行不带参数的操作

问题描述

我有一个没有参数的 GET 方法,并希望在下面工作

/api/books.xml

然而,这适用于正斜杠

/api/books/.xml

[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
    [HttpGet]
    [Route(".{format}")]
    [FormatFilter]
    public ActionResult<List<Book>> Get()
    {
        return bookService.Get();
    }
}

我尝试过的可能解决方案是

  1. 没有 {id} 的注释

    [Route("[controller]/[action].{format}")] // no slash between [action] and .{format}
    
  2. 在 Startup.cs 中添加一个不带 {id} 的默认路由,这样如果 id 参数没有像在这个问题中那样传递,那么路由不应该期望 {action} 之后有斜线。

    app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}");
        });
    

标签: asp.net-web-apiasp.net-coreroutesasp.net-routing

解决方案


根据控制器上当前定义的路由,您描述的是设计使然。

考虑更改路由以匹配所需的 URL 格式

[ApiController]
public class BooksController : ControllerBase {        
    [HttpGet]
    [Route("api/[controller].{format}")] //<--- GET api/books.xml
    [FormatFilter]
    public ActionResult<List<Book>> Get() {
        return bookService.Get();
    }
}

推荐阅读