红花还得绿叶陪衬。vue前端开发离不开数据,这数据正来源于请求web api。为什么采用.net core web api呢?因为考虑到跨平台部署的问题。即使眼下部署到window平台,那以后也可以部署到Linux下。
.net core web api与mvc的web api类似。我把遇到的问题归纳下:
1、部署问题
都说.net core web api,后面我简称api。它有两种部署方式,一个是在iis上部署,另外一个是自托管,类似控制台,通过dotnet run 命令启动的。
1.1 自托管部署
dotnet myapp.dll
网上说,通过hosting.json
复制代码
{
"server.urls": "http://localhost:60000;http://localhost:60001"
}
复制代码
这种方式有个问题,在配置了urls,并没有走配置。
复制代码
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json", optional: true)
.Build();
var host = new WebHostBuilder()
.UseKestrel()
.UseConfiguration(config)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup
()
.Build();
host.Run();
}
复制代码
不过人家是说在Linux环境下的部署,我在window下测试是不行的,不知道是哪的问题,后面可以再研究。
1.2、iis上部署
必须首先安装AspNetCoreModule,搜索这个模块,它的描述如下:
The ASP.NET Core Module allows ASP.NET Core apps to run in an IIS worker process (in-process) or behind IIS in a reverse proxy configuration (out-of-process). IIS provides advanced web app security and manageability features.
这句话大意:api有两种运行模式,一种是运行在iis工作进程中(In-process hosting model),另外一种是通过反向代理配置,运行在外(Out-of-process hosting model)。具体,可参考官方文档。
这是文档中 In-process hosting model图,我们可以看出,http请求首先到达kernel-mode HTTP.sys driver,http监听器,监听器把请求给iis,首先是Asp.NET Core Module接受,然后传递给IISHttpServer,它把请求转换为托管代码,进入.net core middelware pipline,最后才是我们的api代码。换句话说,Asp.NET Core Module类似中间件的作用,它先处理的一部分事情。这是我们项目中采取的部署方案,另外一种模式可能比较复杂,大家阅读官方文档。
2、全局异常处理
我们知道mvc中,有两种异常处理:
使用Global.asax的Application_Error事件进行全局异常处理以及使用HandleErrorAttribute特性捕获全局异常
.net core api中可以编写异常处理的中间件,如下:
View Code
在startup>Configure中添加
app.UseGlobalException();
官网有文档,是这么定义中间件的:
Middleware is software that's assembled into an app pipeline to handle requests and responses
3、安全验证
接口验证,是为了安全性考虑,采用Jwt(Json web token)。
第一步,添加包引用:
第二步,配置:
复制代码
"Issuer": "ElectronInfo",
"Audience": "ElectronInfo",
"SecretKey": "ElectronInfo is a web of shanxi dianzi qingbao weiyuanhui"
复制代码
第三步,在Startup>ConfigureServices中添加授权服务:
复制代码
var jwtSettings = new JwtSettings(){
Issuer=AppSetting.GetConfig("Issuer"),
Audience=AppSetting.GetConfig("Audience"),
SecretKey=AppSetting.GetConfig("SecretKey"),
};
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o => {
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
复制代码
第四步:在Startup>Configure中添加
app.UseAuthentication();
第五步:给整个Controller或者需要接口验证的action中添加
[Authorize]
附:AppSetting类,读取appsettings.json,如下:
View Code
4、日志log4
.net core中本来就支持console输出日志。不过今天我要说的是log4,在传统的.net中普遍使用。
第一步,添加包引用:
第二步,添加配置文件log4net.config:
View Code
第三步,包装以及扩展log4,为了更方便使用:
首先定义一个接口IMLog:
View Code
再定义包装器Log4NetWapper:
View Code
最后定义扩展方法 LogExtensions:
View Code
第四步,在Startup中使用:
复制代码
public static ILoggerRepository repository {get; set; }
public Startup(IConfiguration configuration) {
repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
Configuration = configuration;
}
public IConfiguration Configuration {get; }
复制代码
5、.对net core中startup理解,见官方文档
好了,关于.net core api也是第一次正式使用,就总结到这里。
https://www.cnblogs.com/wangqiang3311/p/10093370.html