c# - 我需要添加什么路由来映射到 API Controller ?

标签 c# asp.net-core asp.net-core-mvc asp.net-core-webapi

我已将 ApiController 添加到我的 asp.net core 2.2 应用程序中,但来自 UI 的异步调用不匹配。

这是我在 Startup.cs 中的路线。

app.UseMvc(config =>
{
    config.MapRoute(
        "Api",
        "api/{controller}/{action}/{id?}"
    );

    config.MapRoute(
        "Default", 
        "{controller=App}/{action=Index}/{id?}"
    );
});

这是向 API Controller 发出各种 GET 请求的 JavaScript 函数之一。

function clearAllFilters() {
  $.get({
    url: "/api/GridFilter/ClearAllFilters",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        console.log('filters cleared');
    }
  });
}

这是 API Controller :

[Route("api/[controller]")]
[ApiController]
public class GridFilterController : ControllerBase
{
    private static readonly string[] FilterFields = {
        // Bunch of strings, omitted for brevity
    };

    [HttpGet]
    public IActionResult ClearAllFilters()
    {
        foreach (string column in FilterFields)
        {
            if (HttpContext.Session.TryGetValue(column, out byte[] savedJson))
            {
                HttpContext.Session.Remove(column);
            }
        }
        return Ok(true);
    }

为什么asp.net不匹配这个?我的网址是/api/controller/action ,它似乎与启动时映射的第一个路由匹配。

最佳答案

你是mixing Conventional Routing and Attribute Routing :

Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed. Actions that define attribute routes cannot be reached through the conventional routes and vice-versa. Any route attribute on the controller makes all actions in the controller attribute routed.

示例中的以下调用配置传统路由模板:

config.MapRoute("Api","api/{controller}/{action}/{id?}");

但是,您已将 GridFilterController 配置为通过使用路由属性 ([Route(...)]) 来使用属性路由:

[Route("api/[controller]")]
[ApiController]
public class GridFilterController : ControllerBase

要从 /api/GridFilter/ClearAllFilters 访问 ClearAllFilters 操作,您有两个常规选项:

  1. 将属性路由模板更改为:

    [Route("api/[controller]/[action]")]
    

    这意味着操作名称将作为路由的一部分包含在内,这与您设置的传统路由模板类似。

  2. 完全删除[Route(...)] 属性。但是,这并不理想,因为您还必须删除 [ApiController] 属性,因为 requires attribute routing .

关于c# - 我需要添加什么路由来映射到 API Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147992/

相关文章:

api - 访问localhost api时如何修复react-native中的网络错误

sql-server - 负载下 .Net Core 容器的 SQL Server DbCommand 超时

visual-studio-2017 - 尝试创建新的空 Controller 时出错 : 'Sequence contains no matching element'

.net - .net核心中的ServicePointManager.DefaultConnectionLimit?

c# - 当 id 具有文件扩展名时,ASP.NET MVC 4 路由不起作用

c# - 通过“转义 cmd\p4v 不会删除\in c#

c# - Azure 函数遇到 System.Net.Sockets.SocketException

asp.net - Azure "~/maintenance"路由失败

c# - 在 .net 中的特定时间做某事

c# - 数据库架构更改后更新 LINQ to SQL 类的最佳方法