Angular .Net核心实体MVC在您的业务逻辑项目中使用定制的本地化,它是一个具有角度前端的多层解决方案
请编辑/改进/更正/调整 我费了很大的劲才把这些片段拼凑起来(我不是一个非常善于编码的人)。正如StackOverflow所鼓励的那样,这是一种分享知识的方式。请编辑/改进/更正 问题是: 情况:多层MVC实体代码优先解决方案,带有角度前端 任务(已接收):在业务逻辑层中,使用本地化来翻译.csv导出的标题,以便我们以后可以将其重新用于我们想要/需要的任何其他内容 我们不使用区域性信息标志,我们使用定制的语言标志,这些标志使用头中的Accept language字段随每个http请求一起传输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请求一起传输 (
(形势和任务都强加给了我)请编辑/改进/更正/调整 参考资料:
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.在业务逻辑类(处理程序)中插入中间件
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 { }