【问题标题】:The web api doesn't routeWeb api 不路由
【发布时间】:2021-10-01 19:25:36
【问题描述】:

我尝试构建一个简单的 API,但路由似乎不起作用,例如在网络浏览器上找不到页面。

例如,当我键入https://localhost:5001/xyz 时,找不到页面。但是,https://localhost:5001/ 有效。

Startup.cs

using denemeWebApp.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using denemeWebApp.Data.Entities;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;


namespace denemeWebApp
{
    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.AddRazorPages();
            services.AddDbContext<MyWorldDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("MyWorldDbConnection"));
            });
            services.AddControllers()
                .AddOData(option => option.Select().Filter().Count().OrderBy().Expand());


            services.AddControllers()
                .AddOData(option => option.Select().Filter()
                    .Count().OrderBy().Expand().SetMaxTop(100)
                    .AddRouteComponents("odata", GetEdmModel()));
        }

        public static IEdmModel GetEdmModel()
        {
            ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<Gadgets>("GadgetsOdata");
            return modelBuilder.GetEdmModel();
        }

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

MyWorldDbContext.cs 使用系统; 使用 denemeWebApp.Data.Entities; 使用 Microsoft.EntityFrameworkCore;

namespace denemeWebApp.Data
{
    public class MyWorldDbContext : DbContext
    {
        public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options) : base(options)
        {

        }
        public DbSet<Gadgets> Gadgets { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // below line to watch the ef core sql quiries generation
            // not at all recomonded for the production code
            optionsBuilder.LogTo(Console.WriteLine);
        }
    }
}

GadgetsController.cs

using denemeWebApp.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;


namespace denemeWebApp.Controllers
{
    [Route("xyz")]
    [ApiController]
    public class GadgetsController : Controller
    {

        private readonly MyWorldDbContext _myWorldDbContext;
        public GadgetsController(MyWorldDbContext myWorldDbContext)
        {
            _myWorldDbContext = myWorldDbContext;
        }

    
        [EnableQuery]
        [HttpGet("Get")]
        public IActionResult Get()
        {
            return Ok(_myWorldDbContext.Gadgets.AsQueryable());
        }
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "MyWorldDbConnection": "Server=localhost,1434;Database=master;Trusted_Connection=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

【问题讨论】:

  • ASP.NET Core 应用在端口 5001 提供 https。http://localhost:5001/ -> https://localhost:5001/
  • 另外,GadgetsController.Get 的路径是 /xyz/Get
  • 另请参阅:stackoverflow.com/a/66086633/5298150 以获取所有计算出的用于调试的路由列表。
  • 抱歉,我找不到问题。你的 Get 方法需要什么 url?
  • @abdusco 没有联系。什么都没有改变

标签: c# rest routes asp.net-core-mvc


【解决方案1】:

您的应用已针对 Razorpages 端点进行了配置。 如果要使用 RazorPages 模板添加控制器,请在 Starup 类的 ConfigureMethod 中添加 MapControllers()

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

之后就可以访问访问路由“https://localhost:5001/xyz/get”

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2021-07-06
    • 2016-12-06
    相关资源
    最近更新 更多