syc_zhaoqianyan 66fc5b3b19 1.扫码枪实现
2.体重秤实现
3.打印机实现
2025-07-01 14:20:07 +08:00

266 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Syc.Basic.Web.WMS.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.Swashbuckle;
using Volo.Abp.UI.Navigation.Urls;
using Volo.Abp.VirtualFileSystem;
using Syc.Abp.Application.Contracts;
using Volo.Abp.Caching;
using Volo.Abp.AspNetCore.Mvc.AntiForgery;
using System.Net;
using StackExchange.Redis;
using Syc.Authorize.JwtBearer;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using Seyounth.Auto.Hs.Runtime.Scanner;
using Syc.Basic.Web.WMS.WebSocket;
using Syc.Core.Tools;
using Seyounth.Auto.Hs.Runtime.Balances;
using Serilog;
using System.Threading.Tasks;
using System.Threading;
using Syc.Basic.Web.WMS.Entitys;
using Microsoft.EntityFrameworkCore.Migrations;
using Volo.Abp.Domain.Repositories;
namespace Syc.Basic.Web.WMS;
[DependsOn(
typeof(JwtBearerAuthenticationModule),
typeof(WMSHttpApiModule),
typeof(AbpAutofacModule),
typeof(WMSApplicationModule),
typeof(WMSEntityFrameworkCoreModule),
typeof(AbpAspNetCoreSerilogModule),
typeof(AbpSwashbuckleModule)
)]
public class WMSHttpApiHostModule : AbpModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
ConfigureRedis();
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
var hostingEnvironment = context.Services.GetHostingEnvironment();
ConfigureUrls(configuration);
ConfigureLocalization();
ConfigureVirtualFileSystem(context);
ConfigureCors(context, configuration);
ConfigureSwaggerServices(context, configuration);
//context.Services.AddHostedService<SyncDataFromDbBackgroupService>();
}
private void ConfigureRedis()
{
Configure<AbpDistributedCacheOptions>(options =>
{
options.KeyPrefix = "WMS.";
});
PreConfigure<ConfigurationOptions>(options =>
{
options.DefaultDatabase = 1;
});
Configure<ConfigurationOptions>(options =>
{
options.DefaultDatabase = 1;
});
}
private void ConfigureUrls(IConfiguration configuration)
{
Configure<AppUrlOptions>(options =>
{
options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"].Split(','));
});
Configure<AbpAntiForgeryOptions>(options => options.AutoValidate = false);
}
private void ConfigureVirtualFileSystem(ServiceConfigurationContext context)
{
var hostingEnvironment = context.Services.GetHostingEnvironment();
if (hostingEnvironment.IsDevelopment())
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.ReplaceEmbeddedByPhysical<WMSDomainSharedModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}services{Path.DirectorySeparatorChar}Syc.Basic.Web.WMS.Domain.Shared"));
options.FileSets.ReplaceEmbeddedByPhysical<WMSDomainModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}services{Path.DirectorySeparatorChar}Syc.Basic.Web.WMS.Domain"));
options.FileSets.ReplaceEmbeddedByPhysical<WMSApplicationContractsModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}services{Path.DirectorySeparatorChar}Syc.Basic.Web.WMS.Application.Contracts"));
options.FileSets.ReplaceEmbeddedByPhysical<WMSApplicationModule>(
Path.Combine(hostingEnvironment.ContentRootPath,
$"..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}services{Path.DirectorySeparatorChar}Syc.Basic.Web.WMS.Application"));
});
}
}
private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddSwaggerGen(
options =>
{
options.ResolveConflictingActions(t => t.First());
options.SwaggerDoc("v1", new OpenApiInfo { Title = "WMS API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "请输入带有Bearer的Token形如 “Bearer {Token}” ",
Name = "Authorization",
In = ParameterLocation.Header,
Scheme = "Bearer",
BearerFormat = "JWT",
Reference = new OpenApiReference()
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
},
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
new[] { "readAccess", "writeAccess" }
}
});
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "Syc.Basic.Web.WMS.Application.xml"); // 添加 swagger xml 注释 这个xml文件开始是不存在的写上项目名.xml即可
});
}
private void ConfigureLocalization()
{
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
options.Languages.Add(new LanguageInfo("en", "en", "English"));
options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi", "in"));
options.Languages.Add(new LanguageInfo("is", "is", "Icelandic", "is"));
options.Languages.Add(new LanguageInfo("it", "it", "Italiano", "it"));
options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
options.Languages.Add(new LanguageInfo("ro-RO", "ro-RO", "Română"));
options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de"));
options.Languages.Add(new LanguageInfo("es", "es", "Español", "es"));
options.Languages.Add(new LanguageInfo("el", "el", "Ελληνικά"));
});
}
private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
app.UseCorrelationId();
app.UseStaticFiles();
app.UseWebSockets();
app.UseRouting();
app.UseCors();
app.UseSpecificationException();
app.UseSwagger();
app.UseAppAuthentication();
app.UseUnitOfWork();
app.UseAbpSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WMS API");
});
app.Map("/ws", c =>
{
c.Use(async (context, next) => {
if (context.WebSockets.IsWebSocketRequest)
{
using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
//X-Correlation-Id
var Correlation = context.Request.Headers["X-Correlation-Id"].FirstOrDefault();
Log.Information($"接收到来自IP{context.Request.Host.Host}的连接");
WebSocketManager.SocketManager?.AddSocket(webSocket, Correlation);
await EchoWebSocket(webSocket);
}
else
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await next();
}
});
});
app.UseAbpSerilogEnrichers();
app.UseConfiguredEndpoints();
}
async Task EchoWebSocket(System.Net.WebSockets.WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
var receiveResult = await webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer), CancellationToken.None);
while (!receiveResult.CloseStatus.HasValue)
{
receiveResult = await webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(
receiveResult.CloseStatus.Value,
receiveResult.CloseStatusDescription,
CancellationToken.None);
}
}