ASP.NET Core学习之二 菜鸟踩坑

简介: 对于像我这样没接触过core的人,坑还是比较多的,一些基础配置和以前差别很大,这里做下记录 一、Startup 1.注册服务 // This method gets called by the runtime.

对于像我这样没接触过core的人,坑还是比较多的,一些基础配置和以前差别很大,这里做下记录

一、Startup

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对比

core1.0和2.0的program写法是不一样的

.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和日志的初始化。

sp.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

 

相关文章
|
10天前
|
消息中间件 前端开发 小程序
一个基于.NET Core构建的简单、跨平台、模块化的商城系统
今天大姚给大家分享一个基于.NET Core构建的简单、跨平台、模块化、完全开源免费(MIT License)的商城系统:Module Shop。
|
10天前
|
算法 C# 数据库
【干货】一份10万字免费的C#/.NET/.NET Core面试宝典
C#/.NET/.NET Core相关技术常见面试题汇总,不仅仅为了面试而学习,更多的是查漏补缺、扩充知识面和大家共同学习进步。该知识库主要由自己平时学习实践总结、网上优秀文章资料收集(这一部分会标注来源)和社区小伙伴提供三部分组成。该份基础面试宝典完全免费,发布两年来收获了广大.NET小伙伴的好评,我会持续更新和改进,欢迎关注我的公众号【追逐时光者】第一时间获取最新更新的面试题内容。
|
10天前
|
数据可视化 网络协议 C#
C#/.NET/.NET Core优秀项目和框架2024年3月简报
公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架源码地址)。注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯🔔)。
|
10天前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
27 0
|
10天前
|
Linux API iOS开发
.net core 优势
.NET Core 的优势:跨平台兼容(Windows, macOS, Linux)及容器支持,高性能,支持并行版本控制,丰富的新增API,以及开源。
30 4
|
10天前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(持续更新)
在这个快速发展的技术世界中,时常会有一些重要的知识点、信息或细节被忽略或遗漏。《C#/.NET/.NET Core拾遗补漏》专栏我们将探讨一些可能被忽略或遗漏的重要知识点、信息或细节,以帮助大家更全面地了解这些技术栈的特性和发展方向。
|
10天前
|
开发框架 中间件 .NET
C# .NET面试系列七:ASP.NET Core
## 第一部分:ASP.NET Core #### 1. 如何在 controller 中注入 service? 在.NET中,在ASP.NET Core应用程序中的Controller中注入服务通常使用<u>依赖注入(Dependency Injection)</u>来实现。以下是一些步骤,说明如何在Controller中注入服务: 1、创建服务 首先,确保你已经在应用程序中注册了服务。这通常在Startup.cs文件的ConfigureServices方法中完成。例如: ```c# services.AddScoped<IMyService, MyService>(); //
106 0
|
10天前
|
开发框架 前端开发 .NET
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
为了便于大家查找,特将之前开发的.Net Core相关的五大案例整理成文,共计440页,32w字,免费提供给大家,文章底部有PDF下载链接。
42 1
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
|
前端开发 .NET Linux
|
前端开发 .NET Linux
【翻译】Asp.net Core介绍
ASP.NET Core is a significant redesign of ASP.NET. This topic introduces the new concepts in ASP.NET Core and explains how they help you develop modern web apps. Asp.net Core是重新设计过得新一代Asp.Net。
1159 0

热门文章

最新文章