【问题标题】:.NET Core 3.1 MVC with Web API Routing not working带有 Web API 路由的 .NET Core 3.1 MVC 不起作用
【发布时间】:2021-10-02 10:41:09
【问题描述】:

之前在 .NET Framework 中工作过,现在我开始使用 .NET Core。

我正在构建一个既是 MVC 又是 Web API 的应用程序,但我的某些路由不起作用。

这是我的控制器代码:

    [Route("api/[controller]")]
    [ApiController]
    public class ClientController : ControllerBase
    {
        private readonly ApplicationDbContext db;
        public ClientController(ApplicationDbContext context)
        {
            db = context;
        }

        [HttpGet]
        public ActionResult Get()
        {
            return Ok("get works");
        }

        [HttpGet]
        public ActionResult Test()
        {
            return Ok("test not working");
        }

        [HttpGet]
        [Route("api/client/input")]
        public ActionResult input(int id)
        {
            return Ok(string.Format("Your id: {0}", id));
        }
    }

这是我的 startup.cs 代码:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseRouting();

            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
  • https://localhost:5001/api/client 有效
  • https://localhost:5001/api/client/test 404 错误
  • https://localhost:5001/api/client/2 404 错误
  • https://localhost:5001/api/client?id=2 404 错误

我已尝试为我的个人操作添加特定路线,但没有效果。

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    你不能为控制器获得任何像这样的路由属性

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

    你可以用 [ApiController] 一起从控制器中移除任何属性路由,或者变成这样

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

    在这种情况下,您可以使用此变体

            [HttpGet]
            public ActionResult Get() //api/client/get
            //or
             [HttpGet("GetAll")]
            public ActionResult Get() //api/client/getall
    
            [HttpGet]
            public ActionResult Test() //api/client/test
            {
                return Ok("test not working");
            }
    

    并修复输入

            [HttpGet]
            [Route("~/api/client/input/{id}")] //api/client/input/4
            public ActionResult input(int id)
    

    但它是一样的

      [HttpGet]
      public ActionResult input(int id)
    

    【讨论】:

    • 如果我删除控制器上的路由,它会给出错误消息:“操作'ProductPOC.Controllers.API.ClientController.Get'没有属性路由。控制器上的操作方法必须使用 ApiControllerAttribute 注释被属性路由。”这对我来说意味着我必须向控制器中的每个端点添加一个路由,这与尝试绑定到某些默认路由是相悖的。
    • @MarkSeymour 你也必须删除 [ApiController] 正如我在回答中问你的那样
    • @MarkSeymour 或者更好的实时 apicontroller 并添加完整路由 [Route("api/[controller]/[action]")]
    • @MarkSeymour 对不起,我没有意识到您使用的是 3.1。请检查我的更新答案。
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多