/// <summary>
        /// Hàm này sẽ kiểm tra dữ liệu vào và ra
        /// ở đây ta sẽ phân loại ngôn ngữ dựa vào URL
        /// </summary>
        /// <param name="context">Injection</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var routeData = context.GetRouteData();
            var language  = routeData.Values["language"] as string;

            var controller      = routeData.Values["controller"] as string;
            var action          = routeData.Values["action"] as string;
            var area            = routeData.Values["area"] as string;
            var endpointFeature = context.Features[typeof(Microsoft.AspNetCore.Http.Features.IEndpointFeature)]
                                  as Microsoft.AspNetCore.Http.Features.IEndpointFeature;

            Microsoft.AspNetCore.Http.Endpoint endpoint = endpointFeature?.Endpoint;

            //Note: endpoint will be null, if there was no
            //route match found for the request by the endpoint route resolver middleware
            if (endpoint != null)
            {
                var routePattern = (endpoint as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern
                                   ?.RawText;

                Console.WriteLine("Name: " + endpoint.DisplayName);
                Console.WriteLine($"Route Pattern: {routePattern}");
                Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
            }

            language = (string.IsNullOrEmpty(language) ? "vi" : language).ToLower();
            var  languageSupport = _localOptions.Value.SupportedCultures;
            bool isSupport       = false;

            for (int i = 0; i < languageSupport.Count(); i++)
            {
                if (languageSupport[i].ToString().ToLower() == language.ToLower())
                {
                    isSupport = true;
                    break;
                }
            }
            language = isSupport ? language : "vi";
            var culture = new CultureInfo(language);

            Thread.CurrentThread.CurrentCulture   = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
            // Cài session
            context.Session.Set <string>("lang", language);
            #region cài cookie lang
            CookieOptions option = new CookieOptions();
            //if (expireTime.HasValue)
            //    option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
            //else
            //    option.Expires = DateTime.Now.AddMilliseconds(10);
            option.Expires = DateTime.Now.AddDays(30);
            context.Response.Cookies.Append("lang", language, option);
            #endregion
            await _next(context);
        }
Example #2
0
        // 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.UseStaticFiles();
            app.UseRouting();
            app.Use((context, next) =>
            {
                var endpointFeature = context.Features[typeof(Microsoft.AspNetCore.Http.Features.IEndpointFeature)]
                                      as Microsoft.AspNetCore.Http.Features.IEndpointFeature;

                Microsoft.AspNetCore.Http.Endpoint endpoint = endpointFeature?.Endpoint;

                //Note: endpoint will be null, if there was no
                //route match found for the request by the endpoint route resolver middleware
                if (endpoint != null)
                {
                    var routePattern = (endpoint as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern
                                       ?.RawText;

                    Console.WriteLine("Name: " + endpoint.DisplayName);
                    Console.WriteLine($"Route Pattern: {routePattern}");
                    Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
                }
                return(next());
            });
            //app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("API GATEWAY");
                });
            });
            app.UseOcelot().Wait();
        }
Example #3
0
        private AuthorizationHandlerContext CreateAuthorizationHandlerContext(Type controllerType, string action)
        {
            var actionContext   = new ActionContext();
            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext.Setup(c => c.Request)
            .Returns(Mock.Of <HttpRequest>());

            actionContext.HttpContext = mockHttpContext.Object;
            actionContext.RouteData   = new RouteData();

            var actionDescriptor = new ControllerActionDescriptor
            {
                ControllerTypeInfo = controllerType.GetTypeInfo(),
                MethodInfo         = controllerType.GetMethod(action)
            };

            actionContext.ActionDescriptor = actionDescriptor;

            var controllerFilters = actionDescriptor.ControllerTypeInfo.CustomAttributes.ToList() ?? new List <CustomAttributeData>();
            var methodFilters     = actionDescriptor.MethodInfo.CustomAttributes.ToList() ?? new List <CustomAttributeData>();
            var endpointMetadata  = new EndpointMetadataCollection(controllerFilters.Union(methodFilters));

            var resource = new Microsoft.AspNetCore.Http.Endpoint(context => Task.CompletedTask, endpointMetadata, action);

            var requirements = new IAuthorizationRequirement[] { new ConventionBasedRequirement() };

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, _userId),
            };
            var user    = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
            var context = new AuthorizationHandlerContext(requirements, user, resource);

            return(context);
        }
Example #4
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseExceptionless();

            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.UseRouting();


            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseAuthentication();
            app.UseAuthorization();
            //EXAMPLE

            //is seems doing this in Program.cs is better
            //authenticate to Azure KeyVault
            // var options = new SecretClientOptions(){
            //     Retry={
            //         Delay = TimeSpan.FromSeconds(2),
            //         MaxDelay = TimeSpan.FromSeconds(16),
            //         MaxRetries = 5,
            //         Mode = RetryMode.Exponential
            //     }
            // };

            // var client = new SecretClient(new Uri("https://kvmykitchen.vault.azure.net/"),new DefaultAzureCredential(),options);
            app.Use((context, next) =>
            {
                var endpointFeature = context.Features[typeof(Microsoft.AspNetCore.Http.Features.IEndpointFeature)]
                                      as Microsoft.AspNetCore.Http.Features.IEndpointFeature;

                Microsoft.AspNetCore.Http.Endpoint endpoint = endpointFeature?.Endpoint;

                //Note: endpoint will be null, if there was no
                //route match found for the request by the endpoint route resolver middleware
                if (endpoint != null)
                {
                    var routePattern = (endpoint as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern
                                       ?.RawText;

                    Console.WriteLine("Name: " + endpoint.DisplayName);
                    Console.WriteLine($"Route Pattern: {routePattern}");
                    Console.WriteLine("Metadata Types: " + string.Join(", ", endpoint.Metadata));
                }
                return(next());
            });


            app.UseEndpoints(endPoints =>
            {
                //for attribute routing
                endPoints.MapControllers();

                //for template based routing
                endPoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=WhatShouldIEat}/{action=DisplayCurrentPrediction}/{id?}"
                    );

                endPoints.MapControllerRoute(
                    name: "index_default",
                    pattern: "{controller}/{action=Index}");

                endPoints.MapControllerRoute(
                    name: "foodItemDetail",
                    pattern: "{controller=FoodItems}/{action=Details}/{id}"
                    );

                endPoints.MapRazorPages();
            });
        }