首页 > 解决方案 > Web api 不路由

问题描述

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

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

启动.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);
        }
    }
}

小工具控制器.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());
        }
    }
}

应用设置.json

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

在此处输入图像描述

标签: c#restroutesasp.net-core-mvc

解决方案


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

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

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


推荐阅读