MapWhen 不工作所有路线

MapWhen Notworking all routes

我需要在一个项目中同时打开网页和 API。但是我对路线有困难。我无法使用 mapwhen 独立设置路由请求。第一路线;我将所有依赖于语言的请求路由到一个控制器。这是我的网页。第二个是默认的 api 路由。

这是我的中间件扩展

public static class WebBuilderMiddlewaresExtension
{
    public static IApplicationBuilder UseWebBuilderMiddlewares(this IApplicationBuilder builder)
    {
        builder.MapWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
        {
            builder.UseRouting();

            builder.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                pattern: "{controller}/{action}/{id?}");

            });
        });
        builder.MapWhen(context => context.Request.RouteValues["culture"] != null || string.IsNullOrEmpty(context.Request.Path), appBuilder =>
        {
            builder.UseRouting();
            builder.UseMiddleware<LanguageMiddleware>();
            builder.UseMiddleware<RouteMiddleware>();
            builder.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "culture-route",
                    pattern: "{culture=tr-TR}/{*default}",
                    defaults: new { culture = "tr-TR", controller = "Home", action = "Index" }
                    );
            });
        });
       

        return builder;
    }

这是我的startup.cs

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        using (var client = new WebBuilderContext())
        {
            client.Database.EnsureCreated();
        }
    }
    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.AddControllersWithViews()
                .AddRazorRuntimeCompilation(); ;
       
        services.AddLocalization(opts => opts.ResourcesPath = "Resources");
        var supportedCultures = new List<CultureInfo>
        {
        new CultureInfo("tr-TR"),
        new CultureInfo("en-US"),
        };
        // Dil ayarlarını ve varsayılan dil seçimini tanımlıyoruz.
        var localizationOptions = new RequestLocalizationOptions
        {
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures,
            DefaultRequestCulture = new RequestCulture("tr-TR"),
        };
        var requestProvider = new RouteDataRequestCultureProvider();
        localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
        
        
        
        services.AddScoped<UiDataService>();
        services.AddDbContext<WebBuilderContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DeveloperMsSql")));
        services.AddSession(options => {
            options.Cookie.Name = "Language";
            options.IdleTimeout = TimeSpan.FromMinutes(30); // Zamanı ayarlayabilirsiniz   
        });
    }

    // 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.UseSession();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseWebBuilderMiddlewares();
       

对于.net core中的api路由,您需要使用路由属性。

这是一个示例(我在 .net core mvc 中添加了一个 api):

    [ApiController]
    [Route("api/[controller]")]
    public class ApiController : ControllerBase
    {
        [HttpGet]
        [Route("Get")]
        public async Task<IActionResult> Get()
        {
            return Ok();
        }
    }

结果: 并更改 mvc 路由,您可以在 startup.cs:

中更改它

配置:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });