Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular .Net核心实体MVC在您的业务逻辑项目中使用定制的本地化,它是一个具有角度前端的多层解决方案_Angular_Asp.net Mvc_Asp.net Core_Localization_Angular Http Interceptors - Fatal编程技术网

Angular .Net核心实体MVC在您的业务逻辑项目中使用定制的本地化,它是一个具有角度前端的多层解决方案

Angular .Net核心实体MVC在您的业务逻辑项目中使用定制的本地化,它是一个具有角度前端的多层解决方案,angular,asp.net-mvc,asp.net-core,localization,angular-http-interceptors,Angular,Asp.net Mvc,Asp.net Core,Localization,Angular Http Interceptors,请编辑/改进/更正/调整 我费了很大的劲才把这些片段拼凑起来(我不是一个非常善于编码的人)。正如StackOverflow所鼓励的那样,这是一种分享知识的方式。请编辑/改进/更正 问题是: 情况:多层MVC实体代码优先解决方案,带有角度前端 任务(已接收):在业务逻辑层中,使用本地化来翻译.csv导出的标题,以便我们以后可以将其重新用于我们想要/需要的任何其他内容 我们不使用区域性信息标志,我们使用定制的语言标志,这些标志使用头中的Accept language字段随每个http请求一起传输 (

请编辑/改进/更正/调整

我费了很大的劲才把这些片段拼凑起来(我不是一个非常善于编码的人)。正如StackOverflow所鼓励的那样,这是一种分享知识的方式。请编辑/改进/更正

问题是:

情况:多层MVC实体代码优先解决方案,带有角度前端 任务(已接收):在业务逻辑层中,使用本地化来翻译.csv导出的标题,以便我们以后可以将其重新用于我们想要/需要的任何其他内容 我们不使用区域性信息标志,我们使用定制的语言标志,这些标志使用头中的Accept language字段随每个http请求一起传输


(形势和任务都强加给了我)

请编辑/改进/更正/调整

参考资料:

  • 在DI容器中配置服务
  • a。在中注册服务 启动方法(请参见单独创建的classDIConfiguration)

    b。在中配置和应用本地化选项 配置方法

  • 定义本地化选项(CustomRequestCultureProvider类)

  • 在适当的项目中构建中间件(业务逻辑)

  • 在同一项目中定义SharedResource.class和resx文件

  • 在业务逻辑类(处理程序)中插入中间件

  • 在DI容器中配置服务 A.在启动方法中注册服务(请参阅创建的单独classDIConfiguration) B在Configure方法中配置和应用本地化选项
  • 使用

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.SpaServices.AngularCli;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();services.AddCors(options =>
                {
                    options.AddPolicy(name: MyAllowSpecificOrigins,
                        builder =>
                        {
                            builder.WithOrigins("http://localhost:4200")
                                   .AllowAnyHeader()
                                   .AllowAnyMethod()
                                   .WithExposedHeaders("Content-Disposition");
                        });
                });
    
                // In production, the Angular files will be served from this directory
                services.AddSpaStaticFiles(configuration =>
                {
                    configuration.RootPath = "ClientApp/dist";
                });
                DiConfiguration.ConfigureServices(Configuration, services);
                AutoMapperConfiguration.ConfigureAutoMapper(services);
                services.AddMediatorAndBehaviour();
            }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                var supportedCultures = new[] { "nl", "en", "fr", "de" };
                var localizationOptions = new RequestLocalizationOptions()
                    .SetDefaultCulture(supportedCultures[0])
                    .AddSupportedCultures(supportedCultures)
                    .AddSupportedUICultures(supportedCultures);
    
                  localizationOptions.RequestCultureProviders.Clear();
    localizationOptions.RequestCultureProviders.Add(new  CustomRequestCultureProvider(localizationOptions));
    
    
                app.UseRequestLocalization(localizationOptions);
    
                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();
                if (!env.IsDevelopment())
                {
                    app.UseSpaStaticFiles();
                }
    
                app.UseAuthentication();
                app.UseRouting();
                app.UseAuthorization();
                app.UseCors(MyAllowSpecificOrigins);
    
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller}/{action=Index}/{id?}");
                });
    
                app.UseSpa(spa =>
                {
             // To learn more about options for serving an Angular SPA from ASP.NET Core,
             // see https://go.microsoft.com/fwlink/?linkid=864501
    
                    spa.Options.SourcePath = "ClientApp";
    
                    if (env.IsDevelopment())
                    {
                        spa.UseAngularCliServer(npmScript: "start");
                    }
                });
    
                app.UseHttpsRedirection();
            }
        }
     
    using System;
    using System.Text;
    …
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Http;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.IdentityModel.Tokens;
    
    public static class DiConfiguration
        {
            public static void ConfigureServices(IConfiguration configuration, IServiceCollection services)
            {
                // Configure Database services
                services.AddDbContextPool<IsisContext>(options => options.UseSqlServer(configuration.GetConnectionString("IsisDatabase")));
    
                services.AddScoped<IIsisUnitOfWork, IsisUnitOfWork>();
                …
                services.AddSingleton<ILocalizationMiddleware, LocalizationMiddleware>();
    
                services.AddControllers();
                services.AddMemoryCache();
                services.AddOptions();
    
                …
    
                services.AddLocalization(options => options.ResourcesPath = "Resources");
            }
    }
    
      4.在同一项目中定义(SharedResource.class可选)资源文件夹和resx文件

      5.在业务逻辑类(处理程序)中插入中间件

  • 以角度(hic)创建HttpInterceptor
  • a。定制httpInterceptor

    import { Injectable } from '@angular/core';
    import {
        HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders
    } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    
    import { CookieService } from 'ngx-cookie-service';
    
    /** Pass untouched request through to the next request handler. */
    @Injectable()
    export class InterceptorHttpheaderAcceptLanguageService implements HttpInterceptor {
        currentLanguage: string;
        constructor(private cookieService: CookieService) {
            this.currentLanguage = this.cookieService.get('lang');
        }
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
        {
            this.currentLanguage = this.cookieService.get('lang');
            const modifiedRequest = req.clone({ setHeaders: { 'Accept-Language': this.currentLanguage } });
            return next.handle(modifiedRequest);
        }
    }
    
    c。注册索引

    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule,
    …
    
    
    ],
      bootstrap: [AppComponent],
      providers: [httpInterceptorProviders],
    })
    export class AppModule { }
    
    public class SomeClass
        {        
            public AdvancedSearchResultDtoToCsvMap(ILocalizationMiddleware localizationMiddleware)
            {
                Map(m => m.Id).Ignore();
                Map(m => m.ArticleCode).Index(0).Name(localizationMiddleware.GetLocalizedString("articlecode").Value);
                Map(m => m.Fullname).Index(1).Name(localizationMiddleware.GetLocalizedString("fullname").Value);
               …
            }
        }
    
    import { Injectable } from '@angular/core';
    import {
        HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders
    } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    
    import { CookieService } from 'ngx-cookie-service';
    
    /** Pass untouched request through to the next request handler. */
    @Injectable()
    export class InterceptorHttpheaderAcceptLanguageService implements HttpInterceptor {
        currentLanguage: string;
        constructor(private cookieService: CookieService) {
            this.currentLanguage = this.cookieService.get('lang');
        }
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
        {
            this.currentLanguage = this.cookieService.get('lang');
            const modifiedRequest = req.clone({ setHeaders: { 'Accept-Language': this.currentLanguage } });
            return next.handle(modifiedRequest);
        }
    }
    
    /* "Barrel" of Http Interceptors */
    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    
    import { JwtInterceptor } from './../../../core/helpers/jwt.interceptor';
    import { ErrorInterceptor } from './../../../core/helpers/error.interceptor';
    import { InterceptorHttpheaderAcceptLanguageService } from './interceptor.httpheader.accept.language.service';
    
    /** Http interceptor providers in outside-in order */
    export const httpInterceptorProviders = [
        { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: InterceptorHttpheaderAcceptLanguageService, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    ];
    
    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule,
    …
    
    
    ],
      bootstrap: [AppComponent],
      providers: [httpInterceptorProviders],
    })
    export class AppModule { }