Asp.Net Core 区域路由到 Api 控制器不起作用

2024-02-16

我有一个托管在某个区域的 API 控制器。然而,路由似乎不起作用,因为我的 ajax 调用在尝试执行控制器操作时不断返回 404。控制器构造函数中的断点永远不会被命中。

[Area("WorldBuilder")]
[Route("api/[controller]")]
[ApiController]
public class WorldApiController : ControllerBase
{
    IWorldService _worldService;
    IUserRepository _userRepository;

    public WorldApiController(IWorldService worldService, IUserRepository userRepository)
    {
        _worldService = worldService;
        _userRepository = userRepository;
    }

    [HttpGet]
    public ActionResult<WorldIndexViewModel> RegionSetSearch()
    {
        string searchTerm = null;
        var userId = User.GetUserId();
        WorldIndexViewModel model = new WorldIndexViewModel();
        IEnumerable<UserModel> users = _userRepository.GetUsers();
        UserModel defaultUser = new UserModel(new Microsoft.AspNetCore.Identity.IdentityUser("UNKNOWN"), new List<Claim>());
        model.OwnedRegionSets = _worldService.GetOwnedRegionSets(userId, searchTerm);
        var editableRegionSets = _worldService.GetEditableRegionSets(userId, searchTerm);
        if (editableRegionSets != null)
        {
            model.EditableRegionSets = editableRegionSets.GroupBy(rs =>
                (users.FirstOrDefault(u => u.IdentityUser.Id == rs.OwnerId) ?? defaultUser)
                    .IdentityUser.UserName)
            .Select(g => new RegionSetCollectionModel(g)).ToList();
        }
        var viewableRegionSets = _worldService.GetViewableRegionSets(userId, searchTerm);
        if (viewableRegionSets != null)
        {
            model.ViewableRegionSets = viewableRegionSets.Where(vrs => vrs.OwnerId != userId).GroupBy(rs =>
                    (users.FirstOrDefault(u => u.IdentityUser.Id == rs.OwnerId) ?? defaultUser)
                        .IdentityUser.UserName)
                .Select(g => new RegionSetCollectionModel(g)).ToList();
        }
        return model;
    }
}

我的startup.cs 文件:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {


        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {

            routes.MapRoute(name: "areaRoute",
              template: "{area}/{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
    }
}

我尝试过以下ajax地址:

   localhost:44344/api/WorldApi/RegionSetSearch
   localhost:44344/WorldBuilder/api/WorldApi/RegionSetSearch
   localhost:44344/api/WorldBuilder/WorldApi/RegionSetSearch
   localhost:44344/WorldBuilder/WorldApi/RegionSetSerarch

对于我尝试的最后一个地址,我从控制器上的路由数据注释中删除了“api/”。

我不确定我在这里做错了什么。我正在遵循我在网上找到的所有示例。


MVC中有两种路由类型,conventions routing这是用于 mvc 和route attribute routing这是用于 Web api 的。

对于配置的区域conventions routingsMVC 不应与路由属性结合使用。路由属性将覆盖默认约定路由。

如果你更喜欢attribute routing, 你可以

[Route("WorldBuilder/api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet("RegionSetSearch")]
    public ActionResult<IEnumerable<string>> RegionSetSearch()
    {
        return new string[] { "value1", "value2" };
    }        
}

注意[HttpGet("RegionSetSearch")]定义了动作RegionSetSearch并在 url 中附加一个占位符。

请求是https://localhost:44389/worldbuilder/api/values/RegionSetSearch

如果你更喜欢conventions routing,你可以删除Route and ApiController like

[Area("WorldBuilder")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> RegionSetSearch()
    {
        return new string[] { "value1", "value2" };
    }        
}

通过这种方式,您需要更改UseMvc like

app.UseMvc(routes => {
    routes.MapRoute("areaRoute", "{area:exists}/api/{controller}/{action}/{id?}");
});

请求是https://localhost:44389/worldbuilder/api/values/RegionSetSearch

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Asp.Net Core 区域路由到 Api 控制器不起作用 的相关文章

随机推荐

  • 3d.io 的航点动画问题

    相机动画始终从初始相机姿势开始 我们不希望出现这种行为 您可以通过以下方式检查此问题 https app 3d io default setup https app 3d io default setup 这段代码以前有效 我们没有改变任何
  • 如何通过chrome扩展自动设置gmail过滤器?

    我想将以下用例实现为 Chrome 扩展 用户访问 Gmail 扩展程序检查当前电子邮件正文中的关键字 如果存在关键字 则添加并保存gmail过滤器 添加标签 存档 此处的详细信息并不重要 第一部分听起来更容易 有谷歌邮箱API https
  • Puppeteer、cloudflare 网站返回 403(禁止)

    我正在尝试从 cloudflare 网站上抓取数据 但无论我做什么 我都会收到 403 禁止错误 我读到这是因为无头请求 有什么办法可以绕过这个吗 我将在下面保留我当前的设置 我还能做些什么来防止被发现吗 const puppeteer r
  • Spring Saml2 和 Spring Session - 未检索到 SavedRequest(身份验证/InResponseTo 异常后无法重定向到请求的页面)

    我正在尝试使用 Spring Boot SAML2 Spring Session 来保护我的 Web 应用程序 将部署在 K8S 上 没有 spring session data rest 或 spring session hazelcas
  • Java:生成具有对数分布的随机数

    我正在尝试生成具有对数分布的随机数 其中 n 1 出现一半的时间 n 2 出现四分之一的时间 n 3 出现八分之一的时间 依此类推 int maxN 5 int t 1 lt lt maxN 2 maxN int n maxN int Ma
  • 有效的 IANA 时区列表

    我正在开发一个支持多时区用户的 Nodejs 系统 目前 我正在使用moment tz names https momentjs com timezone docs using timezones getting zone names 获取
  • AJAX 请求时 Azure SQL 中的间歇性连接超时

    我一直在寻找在对 Azure ASP NET 网站进行 AJAX 调用时间歇性发生的这个错误 今天我终于在日志中发现了它 我怀疑锁阻止了操作 但尝试连接到 Azure SQL 数据库似乎失败 这是异常消息 Timeout expired T
  • 使用流将对象列表转换为从 toString 方法获取的字符串

    Java 8 中有很多有用的新东西 例如 我可以使用流遍历对象列表 然后对对象的特定字段中的值求和 Object的实例 例如 public class AClass private int value public int getValue
  • 仅在一个目录发生更改时运行管道

    所以我有一个具有某种结构的项目 每当我将更改推送到任何文件管道时都会运行 但我希望它仅在特定目录发生更改时运行 有可能吗 The JIRA问题 https jira atlassian com browse BCLOUD 16560指的是这
  • 是否可以获取 formControl 的本机元素?

    我有角反应形式 https angular io docs ts latest cookbook dynamic form html 我创建formControls 并将其分配给输入字段 formControl 据我了解 它创造了nativ
  • 如何用python编写代理池服务器(当请求到来时,选择一个代理来获取url内容)?

    我不知道这种代理服务器的正确名称是什么 欢迎您修复我的问题标题 当我在谷歌上搜索代理服务器时 很多工具都是这样的maproxy https pypi python org pypi maproxy 0 0 12 or 少于 100 行代码的
  • 可达性与 UIDevice-Reachability

    我需要在我的 iPhone 项目中测试网络可达性 使用哪个项目比较好 可达性 http developer apple com library ios samplecode Reachability Introduction Intro h
  • 将数组中数字的所有组合相加

    我正在尝试用 javascript 编写一个程序 从 html 文本区域中获取未指定数量的数字 并尝试所有组合 将所有数字彼此相加 以查看它是否与您指定的数字匹配 现在我可以用文本区域中的字符串创建一个数组并使用for循环我把它们加起来 见
  • Consul healthcheck 运行后状态为“Dead”的 Docker 容器

    我正在使用领事的健康检查功能 并且我不断收到这些 死 容器 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 20fd397ba638 progrium consul latest
  • 现有项目的 XCTest

    我有一个很大的 大约 700 个模块 iOS 项目 现在我需要对现有代码进行单元测试 在我们没有使用它之前 我已经为我的目标添加了新的 XCTest 测试目标 并开始编写我的第一个测试 但是编译后我遇到了一些链接错误 因为我的项目中的模块没
  • 使用 Swift 的没有情节提要或 xib 文件的 OSX 应用程序

    不幸的是 我没有在互联网上找到任何有用的东西 我想知道 在不使用 Swift 中的 Storyboard 或 XIB 文件的情况下 我实际上需要键入哪些代码来初始化应用程序 我知道我必须有一个 swift文件名为main 但我不知道在那里写
  • 针对特定主机向特定用户发送 Nagios 服务通知

    使用 Nagios 我希望能够在特定主机上的服务出现故障时向用户发送通知 然而 另一台主机上的相同服务应该提醒其他人 例如 HostA 已启动 但 Host 上的 www 服务已关闭 gt 通知 UserS HostB 已启动 并且 Hos
  • 有什么方法可以匹配 Visual Fox Pro 和 C# 的 RAND(INT) 方法。网

    我正在将 Visual Fox Pro 代码迁移到 C 网 Visual Fox Pro 的特点是什么 基于文本字符串 在文本框中捕获 生成一个 5 位数字的字符串 48963 如果您始终输入相同的文本字符串 则该字符串将始终为 5 位数字
  • 设置类型的可变长度参数列表

    好吧 我很确定以前已经以某种方式讨论过这个问题 但我显然太愚蠢了 找不到它 首先 我不是在寻找 va list 和其他宏 我正在寻找类似主函数参数的东西 众所周知 默认原型是 int main int argc char argv 现在 我
  • Asp.Net Core 区域路由到 Api 控制器不起作用

    我有一个托管在某个区域的 API 控制器 然而 路由似乎不起作用 因为我的 ajax 调用在尝试执行控制器操作时不断返回 404 控制器构造函数中的断点永远不会被命中 Area WorldBuilder Route api controll