ASP.Net Core Web API 基于约定的路由?

2023-11-27

我错过了什么,我受到了欢迎404对于这个控制器?我真的不想使用基于属性的路由。我也不想action成为任何 URI 的一部分。

我正在使用 Visual Studio 2017 和 .Net Core 1.1。

测试控制器.cs

using System;
using Microsoft.AspNetCore.Mvc;

namespace Foo.Controllers
{
    public class TestController : Controller
    {
        public long Get() => DateTimeOffset.Now.ToUnixTimeSeconds();
    }
}

请注意,这适用于[Route("api/Test")]属性。但我不想使用基于属性的路由。一旦我取消该属性,我就会收到 404。

启动.cs

namespace Foo
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

请注意,这里还有一些 Autofac/DI 的内容,但我将其删除以消除干扰。

调试请求的输出

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3308908Z","tags":{"ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.id":"0HL37O0HBESDL","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request starting HTTP/1.1 GET http://localhost:50129/api/test","severityLevel":"Information","properties":{"DeveloperMode":"true","Host":"localhost:50129","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Hosting.Internal.WebHost","Path":"/api/test","Protocol":"HTTP/1.1","Method":"GET","Scheme":"http"}}}}
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:50129/api/test  
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3633954Z","tags":{"ai.cloud.roleInstance":"Desktop","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.location.ip":"::1","ai.operation.id":"0HL37O0HBESDM","ai.application.ver":"1.0.0.0","ai.internal.nodeName":"Desktop","ai.operation.name":"GET /api/test"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request successfully matched the route with name 'default' and template 'api/{controller}/{id?}'.","severityLevel":"Verbose","properties":{"DeveloperMode":"true","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Routing.RouteBase","RouteName":"default","{OriginalFormat}":"Request successfully matched the route with name '{RouteName}' and template '{RouteTemplate}'.","RouteTemplate":"api/{controller}/{id?}"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3663952Z","tags":{"ai.cloud.roleInstance":"Desktop","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.location.ip":"::1","ai.operation.id":"0HL37O0HBESDM","ai.application.ver":"1.0.0.0","ai.internal.nodeName":"Desktop","ai.operation.name":"GET /api/test"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"No actions matched the current request","severityLevel":"Verbose","properties":{"DeveloperMode":"true","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler","{OriginalFormat}":"No actions matched the current request"}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3693962Z","tags":{"ai.cloud.roleInstance":"Desktop","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.location.ip":"::1","ai.operation.id":"0HL37O0HBESDM","ai.application.ver":"1.0.0.0","ai.internal.nodeName":"Desktop","ai.operation.name":"GET /api/test"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request did not match any routes.","severityLevel":"Verbose","properties":{"DeveloperMode":"true","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Builder.RouterMiddleware","{OriginalFormat}":"Request did not match any routes."}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3753962Z","tags":{"ai.cloud.roleInstance":"Desktop","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.location.ip":"::1","ai.operation.id":"0HL37O0HBESDM","ai.application.ver":"1.0.0.0","ai.internal.nodeName":"Desktop","ai.operation.name":"GET /api/test"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Connection id \"0HL37O0H95P8K\" completed keep alive response.","severityLevel":"Verbose","properties":{"DeveloperMode":"true","ConnectionId":"0HL37O0H95P8K","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Server.Kestrel","{OriginalFormat}":"Connection id \"{ConnectionId}\" completed keep alive response."}}}}
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-03-10T14:18:01.3878990Z","tags":{"ai.cloud.roleInstance":"Desktop","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.location.ip":"::1","ai.operation.id":"0HL37O0HBESDM","ai.application.ver":"1.0.0.0","ai.internal.nodeName":"Desktop","ai.operation.name":"GET /api/test"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Request finished in 54.7982ms 404","severityLevel":"Information","properties":{"DeveloperMode":"true","ElapsedMilliseconds":"54.7982","AspNetCoreEnvironment":"Development","CategoryName":"Microsoft.AspNetCore.Hosting.Internal.WebHost","StatusCode":"404"}}}}
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 54.7982ms 404

这是行不通的,因为未定义到操作方法的映射。 AFAIK,你可以实现WebApiREST就像仅使用属性路由的路由一样,您可以在控制器级别定义它:

[Route("api/[controller]")]
public class TestController : Controller
{
    [HttpGet]
    public long Get() => DateTimeOffset.Now.ToUnixTimeSeconds();
}

Update: 发现了这个github问题Web API 不适用于基于约定的路由 and:

对于 ASP.NET Core MVC,我们决定采用 MVC 5.x 的传统路由方法,而不是 Web API 2.x 的方法。采用传统的路由方式,路由必须同时指定控制器和操作.


您可以将路线模板更改为

template: "api/{controller}/{action}/{id?}"

但在这种情况下,您的 URL 将是/api/test/get.


Update 2(基于guide):您可以包含 NuGet 包Microsoft.AspNetCore.Mvc.WebApiCompatShim并仍然使用 ApiController。代码已开启GitHub如果您对它的作用感到好奇。然后你可以定义WebApi路由:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
        routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.Net Core Web API 基于约定的路由? 的相关文章

随机推荐

  • uniswap 程序集 create2 功能如何工作?

    我正在查看 uniswap 代码 试图理解代码 其中大部分内容都非常清楚 但我确实有一些问题 在这个函数中 function createPair address tokenA address tokenB external returns
  • 在值构造函数中指定类约束

    有没有办法为值构造函数的参数定义类约束 像这样的东西 data Point2D Num a gt Point a a 那么 Point 可以接受任何参数 只要它们属于 Num 类 您可以使用ExistentialQuantification
  • 删除列表中元组的第一个元素

    我有一个元组列表 如下所示 values 1 hi you 2 bye bye 然而 每个元组的第一个元素不是必需的 期望的输出是 hi you bye bye 我已经做了足够的研究 知道我无法操作元组 但我似乎无法找到如何成功删除列表中每
  • 我如何“取消设置”已声明的类

    我有一个完整的表单创建系统 有许多不同的问题类型 我必须检查该人所做的答案是否正确 所有类型的问题都有自己的类 始终称为 ItemClass 并且该类位于其自己的文件中 每次提出问题时 我都会包含该文件 但存在问题 我必须在一个 PHP 文
  • 如何在字符串的特定位置添加字符?

    我正在使用 Notepad 想要使用正则表达式替换在字符串中的特定位置插入字符 比如说 在每行的位置 6 处插入一个逗号 表达式会是什么 如果您想在第六个字符之后添加一个字符 只需使用搜索 6 和替换 1 示例插入一个 从技术上讲 这会将每
  • Java 调试器无法调用某些默认方法实现

    我正在 IntelliJ IDEA 中编码 调试我的应用程序时 我无法使用某些默认方法实现Watches 这是一个浓缩示例 public class Friendship interface Friend default void sayH
  • 如何在 iOS 7 上让 NSTimer 在后台保持活动状态?

    我创建了在后台运行 NSTimer 的应用程序 我使用位置管理器在后台运行 NSTimer 我使用下面的链接在后台运行 NSTimer 如何在 iOS 应用程序中每 n 分钟更新一次后台位置 这种方法在 iOS 6 中工作正常 但在 iOS
  • Activity崩溃生命周期方法-android

    我正在开发一个应用程序 在崩溃的情况下 需要保存崩溃时的一些数据 现在 我将数据保存在 onDestroy 中 如下所示 Override protected void onDestroy saveState super onDestroy
  • Windows Phone 7 中的推送通知问题

    我尝试了以下教程来在 Windows Phone 7 中创建推送通知 http www sgtconker com 2010 03 article windows phone 7 push notifications http www si
  • 如何使用 Inkscape 将 SVG 字符串转换为 jpg

    在花了两天时间尝试使用 ImageMagick 从 SVG 字符串光栅化 jpeg 后 我终于放弃了 虽然我设法使实际转换工作正常 但在渲染图像时 Imagemagick 似乎无法正确转换变换 旋转功能 导致输出与原始 SVG 不同 经过进
  • 将字符串转换为日期时间对象

    我想将此字符串转换为日期时间对象 Wed Oct 20 16 35 44 0000 2010 有没有一种简单的方法可以做到这一点 或者我是否必须编写一个 RE 来解析元素 将 Oct 转换为 10 等等 编辑 strptime 很棒 然而
  • 获取和设置屏幕分辨率

    如何使用 Visual C 收集和更改屏幕分辨率 For 检索屏幕分辨率 您将需要使用System Windows Forms Screen班级 这Screen AllScreens属性可用于访问系统上所有显示的集合 或者您可以使用Scre
  • 获取按下的按键的键值

    我不知道如何获取按下的键的值 我目前有 info price bind keydown function evt alert evt keyCode 但当我按 1 而不是返回 1 时 它返回 49 编辑 我知道键 1 的 Ascii 代码
  • 如何在 Xcode 或 iTunes connect 上获取 Testflight 外部测试器的崩溃日志?

    有什么方法可以知道某人的应用程序出了什么问题 除了这个人之外 其他人的设备都可以使用 该人尝试删除以前的版本并安装新版本 但仍然不起作用 我怀疑我放置在文档文件夹中的文件之一可能仍然存在 但此文件的格式已更改 苹果有一个关于这个名字的技术说
  • 当新的 DLL 复制到 BIN 目录时,ASP.net C# 需要重新启动 IIS

    我们遇到一个问题 每次我们将 dll 复制到 bin 目录时 我们网站上的主域就会停止运行 恢复它的唯一方法是重新启动 WWW Publishing Service 我们运行一个网站 其中包含许多在单个服务器上运行的 IIS 应用程序 其中
  • 如何在 perl 5.24 中关闭“何时是实验性的...”?

    下面的代码直接从 perldoc perl org 上的当前 perlsyn 页面复制 我已经根据需要添加了初始化和声明以使其运行 并且它按预期工作 但重点是 when 关键字 Perl 5 24 抱怨 何时 是实验性的 很公平 但我不想每
  • 在 docker 容器中启动服务失败,出现错误:无法获取 D-Bus 连接:没有与服务管理器的连接

    我安装了docker镜像并成功构建了镜像 当我 ssh 到容器并运行命令时service xxx start 弹出错误 服务 nginfra 启动 重定向到 bin systemctl start nginfra service sbin
  • 从泛型函数中删除一种方法

    我已将以下方法添加到通用函数中speak但现在想删除 REPL 中的这个特定方法 而不删除其余的通用函数的方法 defmethod speak around c courtier string 1 format t Does the Kin
  • 退出应用程序时如何关闭所有Executor?

    根据 Brian Goetz 的 Java Concurrency in Practice在所有 非守护进程 线程终止之前 JVM 无法退出 因此未能关闭执行程序可能会阻止 JVM 退出 IE 如果周围有 Executors System
  • ASP.Net Core Web API 基于约定的路由?

    我错过了什么 我受到了欢迎404对于这个控制器 我真的不想使用基于属性的路由 我也不想action成为任何 URI 的一部分 我正在使用 Visual Studio 2017 和 Net Core 1 1 测试控制器 cs using Sy