MapWhen Notworking all routes

457 views Asked by At

I need to open both web pages and API in a single project. But I have difficulty with the route. I am not able to independently set route requests with mapwhen. First route; I route all language dependent requests to a single controller. This is for my web pages. The second is the default api route.

This My middlewareExtension

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;
    }

This is my 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();
       
1

There are 1 answers

2
Yiyi You On BEST ANSWER

For api route in .net core,you need to use Route Attribute.

Here is a sample(I add an api to .net core mvc):

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

result: enter image description here and change mvc route,you can change it in startup.cs:

Configure:

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