从零开始搭建.NET Core 2.0 API(学习笔记一)
从零开始搭建.NET Core 2.0 API(学习笔记一)
一、 VS 2017 新建一个项目 选择ASP.NET Core Web应用程序,再选择Web API,选择ASP.NET Core 2.0版本
二、 添加API帮助页面 API项目添加 NuGet NSwag.AspNetCore 引用, 然后在添加NSwag设置
运行项目 http://localhost:prot/swagger 即可打开帮助页。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
});
app.UseMvc(route =>
{
route.MapRoute(name: "default", template: "{controller=Home}/{action=Get}/{id?}");
});
}
三、 Startup 类ConfigureServices方法中,添加配置中心初始化;配置中心统一管理配置,便于维护
public IServiceProvider ConfigureServices(IServiceCollection services)
{
ConfigHelper.Init(Configuration["ConfigZookeeperAddress"], Configuration["ConfigNodePath"]);
services.AddSingleton<ILogWrite, LogWrite>(); services.AddMvc(options =>
{
options.Filters.Add<AuthorizationFilter>();
options.Filters.Add<ExceptionFilter>();
options.Filters.Add<PerformanceLogFilter>();
}); var builder = new ContainerBuilder();//实例化 AutoFac 容器
builder.Populate(services); // TODO: 这里添加其他需要注入类的注册 ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
四、添加一个基础设置项目,添加一个日志接口 ILogWrite,一个记录日志实现类 LogWrite 在Startup 类ConfigureServices方法中添加日志 Ioc
因为日志拦截器和异常拦截器会用到日志记录需要注入 所以日志在AddMvc()前面添加,Autofac配置不能在 AddMvc前面,所以这里用.NET Core的Ioc容器,后面Autofac会接管容器。
services.AddSingleton<ILogWrite, LogWrite>();
五、filter 添加三个类分别是
a AuthorizationFilter 权限过滤器
b ExceptionFilter 异常过滤器
c PerformanceLogFilter 性能日志过滤器
ExceptionFilter 、PerformanceLogFilter 分别定义构造函数,注入日志依赖。
public ExceptionFilter(ILogWrite logWrite)
{
_logWrite = logWrite;
} public PerformanceLogFilter(ILogWrite logWrite)
{
_logWrite = logWrite;
}
过滤器必须添加在 Startup类ConfigureServices的services.AddMvc()中
services.AddMvc(options =>
{
options.Filters.Add<AuthorizationFilter>();
options.Filters.Add<ExceptionFilter>();
options.Filters.Add<PerformanceLogFilter>();
});
六、Action参数读取,为了在异常过滤器、性能日志过滤器中,读取参数需要在权限过滤器中添加下面两行代码
public class AuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
HttpRequest request = context.HttpContext.Request;
request.EnableRewind();
request.Body.Position = 0;
}
}
七、性能日志过滤器 PerformanceLogFilter 继承 IActionFilter,实现两个接口
OnActionExecuting 在调用操作方法之前发生
OnActionExecuted 在调用操作方法之后发生
a 在方法 OnActionExecuting中 实例化一个 Stopwatch 用于记录方法开支执行时间
把Stopwatch 实力加入 HttpContext.Items 中,便于在 OnActionExecuted 获取。
b 读取Action请求参数, 放入 HttpContext.Items 中, 不知道为什么OnActionExecuted 去不到参数
/// <summary>
/// 在调用操作方法之前发生。
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{
//
if (SkipLogging(context)) return; var watch = new Stopwatch();
context.HttpContext.Items[ConfigHelper.HttpRequestStopWatcher] = watch;
var paramenters = context.ActionArguments.Count==0?string.Empty:context.ActionArguments.Serialize();
context.HttpContext.Items[ConfigHelper.FilterActionArguments] = paramenters;
watch.Start();
}
OnActionExecuting 中增加了性能日志开关,如果关闭直接返回,不创建Stopwatch,
在OnActionExecuted中回去到的Stopwatch是null 则直接返回(也可以用性能日志开关做判断),不处理后续。
如果Controll、Action添加了NoLog特性,则不记录性能日志
private static bool SkipLogging(ActionExecutingContext actionContext)
{
if (!ConfigHelper.IsPerformanceLog) return true;
return actionContext.ActionDescriptor.GetType().GetCustomAttributes(typeof(NoLogAttribute), false).Any() ||
actionContext.Controller.GetType().GetCustomAttributes(typeof(NoLogAttribute), false).Any();
}
/// <summary>
/// 忽略性能日志记录特性
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
public class NoLogAttribute : Attribute
{
}
八、异常过滤器
/// <summary>
/// 异常拦截器
/// </summary>
public class ExceptionFilter : IExceptionFilter
{
ILogWrite _logWrite;
public ExceptionFilter(ILogWrite logWrite)
{
_logWrite = logWrite;
} /// <summary>
///
/// </summary>
/// <param name="actionExecutedContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public void OnException(ExceptionContext context)
{
BizResult<bool> biz; var paramenters = context.HttpContext.Items[ConfigHelper.FilterActionArguments].ToString();
try
{
biz = new BizResult<bool>(false, (int)B2CBizCode.Exception, context.Exception.Message); if (context.Exception.InnerException != null)
biz.SysMessage += ":" + context.Exception.InnerException.Message; if (ConfigHelper.IsPerformanceLog)
{
var watch = context.HttpContext.Items[ConfigHelper.HttpRequestStopWatcher] as Stopwatch;
watch?.Stop(); var name = context.ActionDescriptor.GetType().GetProperty("ActionName").GetValue(context.ActionDescriptor).ToString(); _logWrite.InfoAsync(new
{
CreateTime = DateTime.Now,
Method = name,
TimeSpan = watch.Elapsed,
IsSuccess = false,
Content = paramenters,
Code = ((B2CBizCode)biz.BusinessCode).ToString(),
Message = biz.BusinessMessage
}.Serialize());
}
}
catch (Exception ex)
{
biz = new BizResult<bool>(false, (int)B2CBizCode.Exception, ex.Message);
}
context.Result = new ApplicationErrorResult(biz); _logWrite?.ErrorAsync($"链接访问出错:{context.HttpContext.Request.Path}", context.HttpContext.Request.Method, this.GetType().Name, context.Exception, paramenters);
return;
}
} public class ApplicationErrorResult : ObjectResult
{
public ApplicationErrorResult(object value) : base(value)
{
StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
九 、添加Autofac,Autofac比.NET Core自带的 Ioc更好用。 NuGetAPI 项目中添加Autofac.Configuration、Autofac.Extensions.DependencyInjection 两个引用 然后 ConfigureServices方法中添加Ioc容器
public IServiceProvider ConfigureServices(IServiceCollection services)
{
ConfigHelper.Init(Configuration["ConfigZookeeperAddress"], Configuration["ConfigNodePath"]);
services.AddSingleton<ILogWrite, LogWrite>(); services.AddMvc(options =>
{
options.Filters.Add<AuthorizationFilter>();
options.Filters.Add<ExceptionFilter>();
options.Filters.Add<PerformanceLogFilter>();
}); var builder = new ContainerBuilder();//实例化 AutoFac 容器
builder.Populate(services); // TODO: 这里添加其他需要注入类的注册 ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
至此.NET Core API的 拦截器、配置管理、日志、Ioc 设置已完成。
public IServiceProvider ConfigureServices(IServiceCollection services) { ConfigHelper.Init(Configuration["ConfigZookeeperAddress"], Configuration["ConfigNodePath"]); services.AddSingleton<ILogWrite, LogWrite>();
services.AddMvc(options => { options.Filters.Add<AuthorizationFilter>(); options.Filters.Add<ExceptionFilter>(); options.Filters.Add<PerformanceLogFilter>(); });
var builder = new ContainerBuilder();//实例化 AutoFac 容器 builder.Populate(services);
// TODO: 这里添加其他需要注入类的注册
ApplicationContainer = builder.Build(); return new AutofacServiceProvider(ApplicationContainer); }
从零开始搭建.NET Core 2.0 API(学习笔记一)的更多相关文章
- node+webpack环境搭建 vue.js 2.0 基础学习笔记
npm install -g vue //全局安装vue npm install -g webpack //全局安装webpack npm install -g vue-cli //全局安装vue-c ...
- Windows录音API学习笔记(转)
源:Windows录音API学习笔记 Windows录音API学习笔记 结构体和函数信息 结构体 WAVEINCAPS 该结构描述了一个波形音频输入设备的能力. typedef struct { W ...
- Windows录音API学习笔记
Windows录音API学习笔记 结构体和函数信息 结构体 WAVEINCAPS 该结构描述了一个波形音频输入设备的能力. typedef struct { WORD wMid; 用于波形 ...
- Windows录音API学习笔记--转
Windows录音API学习笔记 结构体和函数信息 结构体 WAVEINCAPS 该结构描述了一个波形音频输入设备的能力. typedef struct { WORD wMid; 用于波形 ...
- TCP协议和socket API 学习笔记
本文转载至 http://blog.chinaunix.net/uid-16979052-id-3350958.html 分类: 原文地址:TCP协议和socket API 学习笔记 作者:gilb ...
- 【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 上一页 1 2 任务27:Middleware管道介绍 GASA 2019-02-12 20:07 阅读:15 评论:0 任务26:dotne ...
- ASP.NET MVC Web API 学习笔记---第一个Web API程序
http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...
- Node.js API 学习笔记
常用 API 学习笔记 url 函数 url.parse: 解析 url 地址 url.resolve: 向 url 地址添加或替换字段 url.format: 生成 url 地址 querystri ...
- ASP.NET Core 1.0: API的输入参数
Web API是需要接受参数的,譬如,通常用于创建数据的POST method需要接受输入数据,而用于GET method也需要接受一些可选参数,譬如:为了性能起见,控制返回数据的数量是至关重要的. ...
随机推荐
- 第二篇 Mysql常用操作记录(转载)
我们在创建网站的时候,一般需要用到数据库.考虑到安全性,建议使用非root用户.常用命令如下: 1.新建用户 //登录MYSQL@>mysql -u root -p@>密码//创建用户my ...
- Apache Htpasswd生成和验证密码
Assuming you create the password using the following command and "myPassword" as the passw ...
- Oracle OCP提纲
ocp提纲 Oracle SQL 基础 ◆ 标准SQL语言介绍◆ Oracle数据库数据组织形式◆ DDL语句创建表及修改表结构◆ Select语句检索和限制表中数据◆ 从多表中检索数据(连接查询)◆ ...
- Jlink flash 烧录HEX 程序
一般Jlink版本 和 Jag(硬件)最好匹配 安装Jlink 时,IAR的工具包也可以顺带安装. 有源码: IAR 可以自动选择CPU型号,代码直接Download and debug https: ...
- Python-使用unrar库时Couldn't find path to unrar library的解决办法
在Pycharm安装完unrar后,还要安装rar官方的库 不然运行的时候会抛出Couldn't find path to unrar library的错误 Windows: 下载rarlib的库文件 ...
- 如何使用安装光盘为本机创建yum repository
在CentOS 6上可以使用系统安装光盘为本机创建yum repository,创建过程如下. 创建光盘mount点 [root@centos62 ~]# mkdir /media/CentOS mo ...
- C语言学习笔记--#和##操作符
1. #运算符 (1)#运算符用于在预处理期将宏的参数转换为字符串 (2)#的转换作用是在预处理期完成的,因此只在宏定义中有效,即其他地方不能用#运算符 (3)用法:#define STRING(x) ...
- 向linux内核增加一个系统调用-1
验证编辑编译内核的流程,并增加新的系统调用 注意:需要/目录至少10GB空间,/boot目录500MB空间 下载内核并解压 kernel下载 百度云搬运 密码: qc8b 进入 /usr/src目录 ...
- 【Android异常】The specified child already has a parent. You must call removeView() on the child's parent first.
错误信息: Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must ...
- oracle 之sys 、system区别
角色 1)最重要的区别,存储的数据的重要性不同sys--所有oracle的数据字典的基表和视图都存放在sys用户中,这些基表和视图对于oracle的运行是至关重要的,由数据库自己维护,任何用户都不能手 ...