You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DSWMS/Vue.Net/VOL.WebApi/Startup.cs

220 lines
9.1 KiB
C#

2 years ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using VOL.Core.Configuration;
using VOL.Core.Extensions;
using VOL.Core.Filters;
using VOL.Core.Middleware;
using VOL.Core.ObjectActionValidator;
using ConvertHelper;
2 years ago
using Microsoft.AspNetCore.StaticFiles;
2 years ago
namespace VOL.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private IServiceCollection Services { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//<2F><>ʼ<EFBFBD><CABC>ģ<EFBFBD><C4A3><EFBFBD><EFBFBD>֤<EFBFBD><D6A4><EFBFBD><EFBFBD>
services.UseMethodsModelParameters().UseMethodsGeneralParameters();
services.AddSingleton<IObjectModelValidator>(new NullObjectModelValidator());
Services = services;
// services.Replace( ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
services.AddSession();
services.AddMemoryCache();
services.AddHttpContextAccessor();
services.AddMvc(options =>
{
options.Filters.Add(typeof(ApiAuthorizeFilter));
options.Filters.Add(typeof(ActionExecuteFilter));
// options.SuppressAsyncSuffixInActionNames = false;
});
services.AddControllers()
.AddNewtonsoftJson(op =>
{
op.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
SaveSigninToken = true,//<2F><><EFBFBD><EFBFBD>token,<2C><>̨<EFBFBD><CCA8>֤token<65>Ƿ<EFBFBD><C7B7><EFBFBD>Ч(<28><>Ҫ)
ValidateIssuer = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Issuer
ValidateAudience = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Audience
ValidateLifetime = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤ʧЧʱ<D0A7><CAB1>
ValidateIssuerSigningKey = true,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤SecurityKey
ValidAudience = AppSetting.Secret.Audience,//Audience
ValidIssuer = AppSetting.Secret.Issuer,//Issuer<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǰ<EFBFBD><C7B0>ǩ<EFBFBD><C7A9>jwt<77><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret.JWT))
};
options.Events = new JwtBearerEvents()
{
OnChallenge = context =>
{
context.HandleResponse();
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.StatusCode = 401;
context.Response.WriteAsync(new { message = "<22><>Ȩδͨ<CEB4><CDA8>", status = false, code = 401 }.Serialize());
return Task.CompletedTask;
}
};
});
//<2F><><EFBFBD><EFBFBD>appsettings.json<6F><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
string corsUrls = Configuration["CorsUrls"];
if (string.IsNullOrEmpty(corsUrls))
{
throw new Exception("<22><><EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><C3BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǰ<EFBFBD><C7B0>Url");
}
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(corsUrls.Split(","))
//<2F><><EFBFBD><EFBFBD>Ԥ<EFBFBD><D4A4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>
.SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
.AllowCredentials()
.AllowAnyHeader().AllowAnyMethod();
});
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VOL.Core<72><65>̨Api", Version = "v1" });
var security = new Dictionary<string, IEnumerable<string>>
{ { AppSetting.Secret.Issuer, new string[] { } }};
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "JWT<57><54>Ȩtokenǰ<6E><C7B0><EFBFBD><EFBFBD>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD>ֶ<EFBFBD>Bearer<65><72>һ<EFBFBD><D2BB><EFBFBD>ո<EFBFBD>,<2C><>Bearer token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
})
.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressConsumesConstraintForFormFileParameters = true;
options.SuppressInferBindingSourcesForParameters = true;
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
options.ClientErrorMapping[404].Link =
"https://*/404";
});
//ApiBehaviorOptions
}
public void ConfigureContainer(ContainerBuilder builder)
{
Services.AddModule(builder, Configuration);
}
// 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();
}
app.UseMiddleware<ExceptionHandlerMiddleWare>();
app.UseStaticFiles().UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true
});
app.UseDefaultFiles();
app.Use(HttpRequestMiddleware.Context);
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Upload")),
//<2F><><EFBFBD>÷<EFBFBD><C3B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ¼ʱ<C2BC>ļ<EFBFBD><C4BC>б<EFBFBD><D0B1><EFBFBD>
RequestPath = "/Upload",
OnPrepareResponse = (Microsoft.AspNetCore.StaticFiles.StaticFileResponseContext staticFile) =>
{
//<2F><><EFBFBD><EFBFBD><EFBFBD>ڴ˴<DAB4><CBB4><EFBFBD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ<EFBFBD><CFA2><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8><EFBFBD><EFBFBD>֤
// staticFile.File
// staticFile.Context.Response.StatusCode;
2 years ago
},
//FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
//<2F><><EFBFBD>ò<EFBFBD><C3B2><EFBFBD><EFBFBD><EFBFBD>content-type <20><><EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><C3BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>͵<EFBFBD><CDB5>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Dz<EFBFBD><C7B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ô<EFBFBD><C3B4><EFBFBD>ã<EFBFBD><C3A3><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD>ȫ
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><C3BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>apk<70><6B>nupkg<6B><67><EFBFBD>͵<EFBFBD><CDB5>ļ<EFBFBD>
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".apk", "application/vnd.android.package-archive" },
{ ".png", "application/png" }
})
2 years ago
});
2 years ago
2 years ago
//<2F><><EFBFBD><EFBFBD>HttpContext
app.UseStaticHttpContext();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "VOL.Core<72><65>̨Api");
});
app.UseRouting();
//UseCors,UseAuthenticationg<6E><67><EFBFBD><EFBFBD>λ<EFBFBD>õ<EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=ApiHome}/{action=Index}/{id?}");
});
}
}
}