我有一个没有参数的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();
}
}
我尝试过的可能解决方案是
在没有 {id} 的情况下进行批注
[Route("[controller]/[action].{format}")] // no slash between [action] and .{format}
在 Startup 中添加一个没有 {id} 的默认路由.cs这样,如果 id 参数没有像这个问题中那样传递,那么路由不应该期望在 {action} 之后出现斜杠。
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}"); });
根据控制器上当前定义的路由,您描述的内容是设计使然。
考虑更改路由以匹配所需的 URL 格式
[ApiController]
public class BooksController : ControllerBase {
[HttpGet]
[Route("api/[controller].{format}")] //<--- GET api/books.xml
[FormatFilter]
public ActionResult<List<Book>> Get() {
return bookService.Get();
}
}