Patterns for application development with ASP.NET Core
此文章翻译自 NDC { London } 16-20 January 2017 上, Damian Edwards和David Fowler的演讲,如果翻译不周,请大家指出错误。
Logging
生产环境总是配置一个Logger(比如: Serilog, Application Insights)
日志作为诊断应用程序问题的入口
不需要重启应用程序,就能改变日志的级别
在开发环境应该记录尽可能多的日志,但是生产环境出于性能考虑,应该只记录Warning以上的日志
如果不想显示太多的信息,可以选择特定的Category
比如只想调试SQL语句,可以只记录Category为Microsoft.EntityFrameworkCore.*的日志。
ASP.NET按照如下方式记录日志:
ANCM(IIS): 将不能启动进程的错误记录到EventLog
ANCM是指ASP.NET Core Module。按照Damian的说法,当IIS进程无法启动的时候是很崩溃的,此时可以从Windows Event Log中查看具体的错误。
ANCM also uses regular IIS failed request tracing
其他未处理的异常将由为logger providers提供的logger记录
Configuration & Options
随着配置文件的改变而自动重新加载配置
当配置内容的值更改时,使用IOptionsSnapshot重新加载IOptions对象
IOptionsSnapshot是ASP.NET Core 1.1提供的新接口,这个接口在配置文件改变时会重新绑定配置对象的值,这样可以在应用程序运行时动态修改配置内容。
使用User Secrets, 环境变量,Azure KeyVault等方式存储和环境有关的配置内容
比如每个环境的连接字符串,启动的端口不一致,并且这些配置是很少发生改变的,可以配置在环境变量中。
应用程序部署在IIS时,可以通过web.config配置环境变量
File Upload
如果上传的文件需要提供给浏览器访问,将它们放在web root下
最简单的处理文件上传的方法,是使用MVC里的IFormFile或者IFormFileCollection
这2个接口可以直接定义为Action的参数,也可以定义在Model里。
和传统的ASP.NET相比,少了Request.Files。
也可以使用低级别的API,比如HttpRequest.ReadFormAsync和HttpRequest.Form
阻止用户上传任何可以在服务器执行的文件
比较容易疏忽的是.cshtml文件。ASP.NET Core 2.0提供了Razor Page,那么.cshtml文件很可能被制作成一个可以直接访问的Razor Page上传上来。
大文件会提供buffer,防止服务器内存暴增
在保存文件之前,检查客户端传递的文件路径
保证文件上传功能的安全性一直是个斗智斗勇的过程,David演示了一个简单的Hack场景。如果直接使用如下的方式保存文件:
var path = Path.Combine(env.ContentRoot, file.FileName);
当客户端传递来的FileName是"\Views\Home\Index.cshtml"时,你的网站就杯具了。
处理很大的multipart uploads时,不要使用model binding。手动的调用HttpRequest.GetMultipartBoundary()方法。
这个方法仅在ASP.NET CORE 1.1.0提供
IIS的限制仍然生效
这里应该说的是maxRequestSize之类的限制
Dependency Injection
保持你的DI工厂快速响应,不要在构造服务时使用异步方法
如下代码会导致死锁
class Program
{
static void Main(string[] args)
{
DeadlockWithFactory(); Console.WriteLine("hello");
} private static void DeadlockWithFactory()
{
var services = new ServiceCollection();
services.AddSingleton(s =>
{
var b = GetBAsync(s).Result; return new A(b);
}); services.AddSingleton<B>(); var serviceProvider = services.BuildServiceProvider();
var a = serviceProvider.GetService<A>(); //1. 此处lock了Container
} private static async Task<B> GetBAsync(IServiceProvider s)
{
await Task.Delay(1000); //2. 此处由于使用了await关键字,离开了主线程,进入了后台线程 return s.GetRequiredService<B>(); //3. 此处后台线程尝试lock Container,导致死锁
}
} public class A
{
public A(B b)
{ }
} public class B
{ }
避免手动的调用GetService
这里的大概意思是,由于手动调用GetService依赖了IServiceProvider,会使得单元测试变复杂。
有些场景下,我们不需要在构造函数注入服务,而是想在执行到特定方法的时候才注入。Controller层面有个FromServices特性可以标记在Action的参数上。如果是下层代码,则可以自己定义一个XXXProvider,提供一个ResolveXXX方法,那么只需要在构造函数注入XXXProvider即可。这种方式适用于构造数据库连接,打开文件等。
实现了IDisposable接口的服务会由Container控制调用它们的Dispose方法,如果在顶层Container中构造出该服务的实例,会导致内存泄漏。
Container构造的服务,会在Container释放的时候自动释放。如果在ApplicationServices上构造出的实例,在应用停止后才会释放。
Turn on scope validation to make sure you don't have scoped services capturing singletons.
想像一下这个场景
var services = new ServiceCollection();
services.AddSingleton<A>();
services.AddScoped<B>(); var sp = services.BuildServiceProvider();
var a = sp.GetRequiredService<A>();
如果A依赖了B,那么本应该是Scoped的B类型被捕获成了单例。
在ASP.NET Core 1.1中, BuildServiceProvider方法提供了一个新的参数 validateScopes,上面的代码可以修改成
var sp = services.BuildServiceProvider(validateScopes: true);
var a = sp.GetRequiredService<A>(); //如果A依赖B,那么此处会抛出System.InvalidOperationException: Cannot consume scoped service 'B' from singleton 'A'.
优化依赖注入
构造函数注入
public class A(B b) { }
public class B(C c) { }
public class C() { }
等同于
new A(new B(new C()));
ServiceProvider注入
public class A(IServiceProvider sp) { _b = sp.GetService<B>(); }
public class B(IServiceProvider sp) { _c = sp.GetService<C>(); }
public class C() { }
等同于
new C();
new B(GetService<C>());
new A(GetService<B>());
MVC
Protect against mass assignment with separate input/output models
在现有MVC模式中,我们一般定义一个ViewModel来展示整个页面需要显示的内容,再定义一些Model存储客户端传递的参数。我们要尽量避免这个过程中产生的重复编码。
public class AdminViewModel
{
[Display(Name = "Live Show Embed URL", Description = "URL for embedding the live show")]
[DataType(DataType.Url)]
public string LiveShowEmbedUrl { get; set; } [Display(Name = "Live Show HTML", Description = "HTML content for the live show")]
[DataType(DataType.MultilineText)]
public string LiveShowHtml { get; set; } [Display(Name = "Next Show Date/time", Description = "Exact date and time of the next live show in Pacific Time")]
[DateAfterNow(TimeZoneId = "Pacific Standard Time")]
public DateTime? NextShowDatePst { get; set; } [Display(Name = "Standby Message", Description = "Message to show on home page during show standby")]
public string AdminMessage { get; set; } public string NextShowDateSuggestionPstAM { get; set; } public string NextShowDateSuggestionPstPM { get; set; } public string SuccessMessage { get; set; } public bool ShowSuccessMessage => !string.IsNullOrEmpty(SuccessMessage); public AppSettings AppSettings { get; set; } public string EnvironmentName { get; set; }
} [ModelMetadataType(typeof(AdminViewModel))]
public class AdminInputModel
{
public string LiveShowEmbedUrl { get; set; } public string LiveShowHtml { get; set; } public DateTime? NextShowDatePst { get; set; } public string AdminMessage { get; set; }
}
在这个例子中,在Get请求时需要返回一个包含了所有展示内容的AdminViewModel,在Post请求时只需要客户端传递部分参数,因此可以定义一个AdminInputModel,同时指定ModelMetadataType(typeof(AdminViewModel)),这样验证的Attribute可以从AdminViewModel中自动复制过来,避免重复编码。
同时,推荐大家采用类似AutoMapper之类的第三方库解决对象复制、克隆过程中产生的重复编码。
在上述代码中,我更倾向于以如下的方式定义Model
public class AdminViewModel
{
public AdminInputModel Input { get; set; } public string NextShowDateSuggestionPstAM { get; set; } public string NextShowDateSuggestionPstPM { get; set; } public string SuccessMessage { get; set; } public bool ShowSuccessMessage => !string.IsNullOrEmpty(SuccessMessage); public AppSettings AppSettings { get; set; } public string EnvironmentName { get; set; }
} [ModelMetadataType(typeof(AdminViewModel))]
public class AdminInputModel
{
[Display(Name = "Live Show Embed URL", Description = "URL for embedding the live show")]
[DataType(DataType.Url)]
public string LiveShowEmbedUrl { get; set; } [Display(Name = "Live Show HTML", Description = "HTML content for the live show")]
[DataType(DataType.MultilineText)]
public string LiveShowHtml { get; set; } [Display(Name = "Next Show Date/time", Description = "Exact date and time of the next live show in Pacific Time")]
[DateAfterNow(TimeZoneId = "Pacific Standard Time")]
public DateTime? NextShowDatePst { get; set; } [Display(Name = "Standby Message", Description = "Message to show on home page during show standby")]
public string AdminMessage { get; set; }
}
TagHelpers
- 正确的处理属性值
- 属性中带有文件路径时,确保在执行前验证文件是否存在
在Post-Redirect-Get场景中使用TempData
当你在一个Post的请求里完成操作,并且需要重定向到另外一个页面展示操作结果时,可以通过URL传参,Cookies, Sessions等技术来实现,也可以使用TempData来实现。
ASP.NET Core的TempData是基于Cookies的。
Testing your pipeline
使用TestHost在内存中测试整个管道,而不用访问网络
[Fact]
public async Task VerifyResponse()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>(); var server = new TestServer(builder);
var client = server.CreateClient(); var response = await client.GetAsync("http://something"); Assert.Equal("Hello World", await response.Content.ReadAsStringAsync());
}
单元测试中也可以使用enviroments来对不同的环境进行测试
[Fact]
public async Task VerifyTestEnvironmentResponse()
{
var builder = new WebHostBuilder()
.UseEnvironment("Test")
.UseStartup<StartupWithEnvironment>(); var server = new TestServer(builder);
var client = server.CreateClient(); var response = await client.GetAsync("http://something"); Assert.Equal("Test", await response.Content.ReadAsStringAsync());
}
Per request state
HttpContext.Items
和以往一样,可以将与会话相关的数据存储在HttpContext.Items
HttpContext.Get/SetFeature
通过调用HttpContext.Features.Set方法添加自定义的行为
Scoped services
每个会话开始会构造一个Scope,会话结束会释放该Scope。因此和会话相关的服务最好注册为Scoped。
在Request Context以外要访问HttpContext时,可以使用IHttpContextAcessor接口。
public class A
{
private HttpContext HttpContext { get; set; } public A(IHttpContextAcessor httpContextAcessor)
{
this.HttpContext = httpContextAcessor.HttpContext;
}
}
备注
Patterns for application development with ASP.NET Core的更多相关文章
- Prerender Application Level Middleware - ASP.NET Core Middleware
In the previous post Use Prerender to improve AngularJS SEO, I have explained different solutions at ...
- [转]Session and application state in ASP.NET Core
本文转自:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state By Rick Anderson and Steve ...
- 使用Azure Application Insignhts监控ASP.NET Core应用程序
Application Insignhts是微软开发的一套监控程序.他可以对线上的应用程序进行全方位的监控,比如监控每秒的请求数,失败的请求,追踪异常,对每个请求进行监控,从http的耗时,到SQL查 ...
- Working with Data » 使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程
原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web applica ...
- [转]ASP.NET Core 1 Deploy to IIS
本文转自: http://webmodelling.com/webbits/aspnet/aspnet-deploy-iis.aspx 15 Sep 2016. This tutorial will ...
- 翻译 - ASP.NET Core 基本知识 - 配置(Configuration)
翻译自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0 ASP ...
- ASP.NET Core 1.0 入门——了解一个空项目
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- ASP.NET Core 2 学习笔记(二)生命周期
要了解程序的运行原理,就要先知道程序的进入点及生命周期.以往ASP.NET MVC的启动方式,是继承 HttpApplication 作为网站开始的进入点,而ASP.NET Core 改变了网站的启动 ...
- ASP.NET Core 2 学习笔记(十一)Cookies & Session
基本上HTTP是没有记录状态的协定,但可以通过Cookies将Request来源区分出来,并将部分数据暂存于Cookies及Session,是写网站常用的用户数据暂存方式.本篇将介绍如何在ASP.NE ...
随机推荐
- JVM 体系结构
JVM 是一种抽象的计算机,基于堆栈架构,它有自己的指令集和内存管理,是 Java 跨平台的依据,JVM解释执行字节码,或将字节码编译成本地代码执行.Java 虚拟机体系结构如下: Class Fil ...
- 1218: [HNOI2003]激光炸弹
1218: [HNOI2003]激光炸弹 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1139 Solved: 542[Submit][Statu ...
- 1067: [SCOI2007]降雨量
1067: [SCOI2007]降雨量 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 2148 Solved: 554[Submit][Status] ...
- 长连接 Socket.IO
概念 说到长连接,对应的就是短连接了.下面先说明一下长连接和短连接的区别: 短连接与长连接 通俗来讲,浏览器和服务器每进行一次通信,就建立一次连接,任务结束就中断连接,即短连接.相反地,假如通信结束( ...
- idiom - Initialization-on-demand holder 延迟加载的单例模式
参考:https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom idiom - 一个线程安全的.无需synchroniza ...
- 跨平台的.NET邮件协议MailKit组件解析
发起的.NET Core开源组织号召,进展的速度是我自己也没有想到的,很多园友都积极参与(虽然有些人诚心砸场子,要是以我以前的宝脾气,这会应该被我打住院了吧,不过幸好是少数,做一件事总有人说好,也有人 ...
- Spring Boot启动过程(六):内嵌Tomcat中StandardHost与StandardContext的启动
看代码有助于线上出现预料之外的事的时候,不至于心慌... StandardEngine[Tomcat].StandardHost[localhost]的启动与StandardEngine不在同一个线程 ...
- Java第一次作业
(一)学习总结 1.在java中通过Scanner类完成控制台的输入,Scanner类实现基本数据输入的方法是什么? import java.util.Scanner; System.out.prin ...
- JAVA-Servlet-过滤器知识总结
JAVA Filter是什么呢? Servlet过滤器实际上就是一个标准的java类,这个类通过实现Filter接口获得过滤器的功能.它在jsp容器启动的时候通过web.xml配置文件被系统加载.Se ...
- English Learn
English Learn 一直决定好好学习英语.越来越觉得英语的重要性,解决日常问题.学习新东西.使用google时都经常碰到英文.所以觉得在blog上记录些学习英语的文章,也算是对自己的一种监督. ...