ASP.NET Core学习之二 菜鸟踩坑
对于像我这样没接触过core的人,坑还是比较多的,一些基础配置和以前差别很大,这里做下记录
一、Startup
Startup.cs 文件是 ASP.NET Core 的项目的入口启动文件
1.注册服务
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- // services.AddTransient<IUser, User>();
- //services.AddSingleton<IUser>(new User());
- services.AddSingleton<IUser, User>();
- //services.AddScoped<>();//作用域注入
- services.AddMemoryCache(); //MemoryCache缓存注入
- }
2.配置HTTP请求管道
听起来很蒙,其实就是用于处理我们程序中的各种中间件,它必须接收一个IApplicationBuilder参数,我们可以手动补充IApplicationBuilder的Use扩展方法,将中间件加到Configure中,用于满足我们的需求。
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseBrowserLink();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- }
- app.UseStaticFiles();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
3.自定义配置文件
类似于web.config
- ///IHostingEnvironment获取环境变量信息,没错就是获取环境变量
- public Startup(IHostingEnvironment env)
- {
- //这里创建ConfigurationBuilder,其作用就是加载Congfig等配置文件
- var builder = new ConfigurationBuilder()
- //env.ContentRootPath:获取当前项目的跟路径
- .SetBasePath(env.ContentRootPath)
- //使用AddJsonFile方法把项目中的appsettings.json配置文件加载进来,后面的reloadOnChange顾名思义就是文件如果改动就重新加载
- .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
- .AddEnvironmentVariables();
- //这返回一个配置文件跟节点:IConfigurationRoot
- Configuration = builder.Build();
- }
二、Program
1. core1.0和2.0对比
Program.cs这个文件包含了 ASP.NET Core 应用的 Main 方法,负责配置和启动应用程序。
core1.0和2.0的program写法是不一样的(如下),但是本质是一样的,目的都是创建一个WebHostBuilder(WEB主机构建器,自己翻译的,呵呵),然后进行构建(Build),最后运行(Run)
.net core 1.0
- public static void Main(string[] args)
- {
- var host = new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseIISIntegration()
- .UseStartup<Startup>()
- .UseApplicationInsights()
- .Build();
- host.Run();
- }
.net core 2.0
- public static void Main(string[] args)
- {
- BuildWebHost(args).Run();
- }
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<Startup>()
- .Build();
看一下WebHost.CreateDefaultBuilder(args)的源码:
- public static IWebHostBuilder CreateDefaultBuilder(string[] args)
- {
var builder = new WebHostBuilder()- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .ConfigureAppConfiguration((hostingContext, config) =>
- {
var env = hostingContext.HostingEnvironment;- config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())- {
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)- {
- config.AddUserSecrets(appAssembly, optional: true);
- }
- }
- config.AddEnvironmentVariables();
if (args != null)- {
- config.AddCommandLine(args);
- }
- })
- .ConfigureLogging((hostingContext, logging) =>
- {
- logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
- logging.AddConsole();
- logging.AddDebug();
- })
- .UseIISIntegration()
- .UseDefaultServiceProvider((context, options) =>
- {
- options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
- });
- return builder;
- }
可看到2.0不过是被封装了,使用静态方法实现,还集成了appsettings和日志的初始化。在2.1里面做了更多的处理。
asp.net core 自带了两种http servers, 一个是WebListener,在2.0中重命名为HTTP.sys , 可以使用来实现,它只能用于windows系统, 另一个是kestrel, 它是跨平台的.
2. Kestrel
支持特性
- HTTPS
- Opaque upgrade used to enable WebSockets
- Unix sockets for high performance behind Nginx
kestrel是默认的web server, 就是通过UseKestrel()这个方法来启用的.
但是我们开发的时候使用的是IIS Express, 调用UseIISIntegration(),启用IIS Express, 它作为Kestrel的Reverse Proxy server来用;
如果在windows服务器上部署的话, 就应该使用IIS作为Kestrel的反向代理服务器来管理和代理请求,和原IIS工作进程是分开的,通过ASP.NET Core Module (ANCM) 来控制core程序;
此图 说明了 IIS, ANCM 和ASP.NET Core 应用程序直接的关系
Requests come in from the Web and hit the kernel mode Http.Sys driver which routes them into IIS on the primary port (80) or SSL port (443). ANCM forwards the requests to the ASP.NET Core application on the HTTP port configured for the application, which is not port 80/443.
Kestrel listens for traffic coming from ANCM. ANCM specifies the port via environment variable at startup, and the UseIISIntegration method configures the server to listen on http://localhost:{port}
. There are additional checks to reject requests not from ANCM. (ANCM does not support HTTPS forwarding, so requests are forwarded over HTTP even if received by IIS over HTTPS.)
注:大体意思是从80/443端口进来,然后ANCM通过 指定的端口 与程序进行交互,其中IISIntegration通过监听该端口,拒绝掉不是来自ANCM的请求。
如果在linux上的话, 可以使用apache, nginx等等的作为kestrel的proxy server,使用ForwardedHeaders中间件做处理,具体可以看官网怎么在linux下部署的文档;
当然也可以单独使用kestrel作为web 服务器, 但是使用iis作为reverse proxy还是由很多有点的: 例如,IIS可以过滤请求, 管理证书, 程序崩溃时自动重启等.
3. HTTP.sys
HTTP.sys, 是通过UseKestrel()这个方法来启用的。但它不能与IIS 或者IIS Express 使用,也不能使用ANCM。
HTTP.sys 支持以下特性:
- Windows Authentication
- Port sharing
- HTTPS with SNI
- HTTP/2 over TLS (Windows 10)
- Direct file transmission
- Response caching
- WebSockets (Windows 8)
支持的Windows 版本:
- Windows 7 and Windows Server 2008 R2 and later
三、使用日志
- public class HomeController : Controller
- {
- public HomeController()
- {
- ILoggerFactory loggerFactory = new LoggerFactory().AddConsole().AddDebug();
- _logger = loggerFactory.CreateLogger<HomeController>();
- _logger.LogInformation("================");
- _logger.LogInformation("LOGGER IS START");
- _logger.LogInformation("================");
- }
- }
四、Routing
路由有两种方式: Convention-based (按约定), attribute-based(基于路由属性配置的).
其中convention-based (基于约定的) 主要用于MVC (返回View或者Razor Page那种的).
Web api 推荐使用attribute-based.
这种基于属性配置的路由可以配置Controller或者Action级别, uri会根据Http method然后被匹配到一个controller里具体的action上.
常用的Http Method有:
Get, 查询, Attribute: HttpGet, 例如: '/api/product', '/api/product/1'
POST, 创建, HttpPost, '/api/product'
PUT 整体修改更新 HttpPut, '/api/product/1'
PATCH 部分更新, HttpPatch, '/api/product/1'
DELETE 删除, HttpDelete, '/api/product/1
还有一个Route属性(attribute)也可以用于Controller层, 它可以控制action级的URI前缀.
问题:继承api控制器后,只能使用Http Method,不能使用其他名称,或者是我不懂运用,比如GetUser
参考:
http://blog.csdn.net/sd7o95o/article/details/78190862
http://blog.csdn.net/sd7o95o/article/details/78190862
ASP.NET Core学习之二 菜鸟踩坑的更多相关文章
- ASP.NET Core学习系列
.NET Core ASP.NET Core ASP.NET Core学习之一 入门简介 ASP.NET Core学习之二 菜鸟踩坑 ASP.NET Core学习之三 NLog日志 ASP.NET C ...
- [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参
[转]ASP.NET MVC学习系列(二)-WebAPI请求 传参 本文转自:http://www.cnblogs.com/babycool/p/3922738.html ASP.NET MVC学习系 ...
- WebAPI调用笔记 ASP.NET CORE 学习之自定义异常处理 MySQL数据库查询优化建议 .NET操作XML文件之泛型集合的序列化与反序列化 Asp.Net Core 轻松学-多线程之Task快速上手 Asp.Net Core 轻松学-多线程之Task(补充)
WebAPI调用笔记 前言 即时通信项目中初次调用OA接口遇到了一些问题,因为本人从业后几乎一直做CS端项目,一个简单的WebAPI调用居然浪费了不少时间,特此记录. 接口描述 首先说明一下,基于 ...
- ASP.NET Core学习指导
ASP.NET Core 学习指导 "工欲善其事必先利其器".我们在做事情之前,总应该做好充分的准备,熟悉自己的工具.就像玩游戏有一些最低配置一样,学习一个新的框架,也需要有一些基 ...
- Asp.Net Core学习笔记:入门篇
Asp.Net Core 学习 基于.Net Core 2.2版本的学习笔记. 常识 像Django那样自动检查代码更新,自动重载服务器(太方便了) dotnet watch run 托管设置 设置项 ...
- ASP.NET Core学习之三 NLog日志
上一篇简单介绍了日志的使用方法,也仅仅是用来做下学习,更何况只能在console输出. NLog已是日志库的一员大佬,使用也简单方便,本文介绍的环境是居于.NET CORE 2.0 ,目前的版本也只有 ...
- ASP.NET Core学习之一 入门简介
一.入门简介 在学习之前,要先了解ASP.NET Core是什么?为什么?很多人学习新技术功利心很重,恨不得立马就学会了. 其实,那样做很不好,马马虎虎,联系过程中又花费非常多的时间去解决所遇到的“问 ...
- ASP.NET Core部署系列二:发布到CentOS上
前言: 在上一节中,通过一系列的步骤,已经将项目部署到IIS上,虽然遇到了一些问题,但最终解决并成功运行了.而在这一节中,将尝试通过linux系统的环境下,部署项目,实现Net Core跨平台的亮点. ...
- ASP.NET MVC学习系列(二)-WebAPI请求
继续接着上文 ASP.NET MVC学习系列(一)-WebAPI初探 来看看对于一般前台页面发起的get和post请求,我们在Web API中要如何来处理. 这里我使用Jquery 来发起异步请求实现 ...
随机推荐
- linux API函数大全
获取当前执行路径:getcwd1. API之网络函数 WNetAddConnection 创建同一个网络资源的永久性连接 WNetAddConnection2 创建同一个网络资源的连接 WNetAdd ...
- Oracle table names are case sensitive (normally all uppercase)
oracle_fdw error desc: postgres=# select * from test; ERROR: Oracle table "sangli"." ...
- 一个js的动画,以前以为只有flash可以实现
11年刚干这行的时候,看到这种什么百叶窗的动画,以为都是flash实现的,最近突然灵光一闪,想到了用js实现(虽然我不是做前端的,本人做.net).代码虽然实现了,但是比较乱,先上个图: 代码主要就是 ...
- 好好写代码吧,没事别瞎B去创业!
知乎上看到这个问题 正好最近想写篇关于此的文章,于是就回答了一波. 也贴到这里来,回答如下 : 本问题简直为我量身定制,做为一个正在创业中的苦逼少年,说说我是如何从鼓吹怂恿身边人创业转换成反对创业的. ...
- Java进阶(七)正确理解Thread Local的原理与适用场景
原创文章,始自发作者个人博客,转载请务必将下面这段话置于文章开头处(保留超链接). 本文转发自技术世界,原文链接 http://www.jasongj.com/java/threadlocal/ Th ...
- Hadoop 少量map/reduce任务执行慢问题
最近在做报表统计,跑hadoop任务. 之前也跑过map/reduce但是数据量不大,遇到某些map/reduce执行时间特别长的问题. 执行时间长有几种可能性: 1. 单个map/reduce任务处 ...
- lua 中pairs 和 ipairs差别
ipairs 和pairs在lua中都是遍历tbale的函数可是两者有差别 1.pairs遍历table中的全部的key-vale 而ipairs会依据key的数值从1開始加1递增遍历相应的table ...
- Jenkins具体安装与构建部署使用教程
Jenkins是一个开源软件项目.旨在提供一个开放易用的软件平台,使软件的持续集成变成可能. Jenkins是基于Java开发的一种持续集成工具,用于监控持续反复的工作,功能包含:1.持续的软件版本号 ...
- 如何通过PowerShell获取Office 365 TenantID
作者:陈希章 发表于2017年5月31日 安装Azure Powershell 模块 Installing the Azure PowerShell Service Management module ...
- ASP.NET Core WebApi 返回统一格式参数
业务场景: 业务需求要求,需要对 WebApi 接口服务统一返回参数,也就是把实际的结果用一定的格式包裹起来,比如下面格式: { "response":{ "code&q ...