微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

属性路由未正确映射

如何解决属性路由未正确映射

我的 Startup.cs 设置如下:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace BotApiV2
{
    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.AddMvcCore()
                .AddApiExplorer();

            services.AddRazorPages();
            services.AddSwaggerGen();
        }

        // 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("/Error");
            }

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json","My API V1");
            });

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

我的控制器是这样设置的:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using BotApiV2.DataLayer;

namespace BotApiV2
{
[ApiExplorerSettings(IgnoreApi = false,GroupName = nameof(ValuesController))]
[Route("api/values")]
public class ValuesController : ControllerBase
{
    [HttpGet]
    [Route("test")]
    public ActionResult test()
    {
        var x = new BotDatabaseContext();
        
        var t = new Dictionary<string,string>
        {
            { "test1","value1" },{ "test2","value2" },{ "test3","value3" }
        };
        return new JsonResult(t);
    }
}
}

但是无法找到对 /api/values/test 的浏览。有什么设置错误吗?我的目标是 .NET 5.0(我也尝试过 .NET Core 3.1,结果相同)。

解决方法

您在启动时映射了剃刀页面路由。如果你想让你的控制器路由工作,你需要映射你的控制器路由。

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。