DotNETCore 学习笔记 Startup、中间件、静态文件
Application Startup Startup Constructor - IHostingEnvironment - ILoggerFactory ConfigureServices - IServiceCollection Configure - IApplicationBuilder - IHostingEnvironment - ILoggerFactory ---------------------------------------------------------------------------------------- Middleware public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
}); --will not execute
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World, Again!");
});
} public void ConfigureLogInline(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information);
var logger = loggerfactory.CreateLogger(_environment);
app.Use(async (context, next) =>
{
logger.LogInformation("Handling request.");
await next.Invoke();
logger.LogInformation("Finished handling request.");
}); app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
} Run:
*********************************************************************************************
The following two middleware are equivalent as the Use version doesn’t use the next parameter:
public void ConfigureEnvironmentOne(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
} public void ConfigureEnvironmentTwo(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
}
*********************************************************************************************
Map:
private static void HandleMapTest(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Map Test Successful");
});
} public void ConfigureMapping(IApplicationBuilder app)
{
app.Map("/maptest", HandleMapTest); } private static void HandleBranch(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Branch used.");
});
} public void ConfigureMapWhen(IApplicationBuilder app)
{
app.MapWhen(context => {
return context.Request.Query.ContainsKey("branch");
}, HandleBranch); app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
} You can also nest Maps: app.Map("/level1", level1App => {
level1App.Map("/level2a", level2AApp => {
// "/level1/level2a"
//...
});
level1App.Map("/level2b", level2BApp => {
// "/level1/level2b"
//...
});
});
********************************************************************************************* public class RequestLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger; public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>();
} public async Task Invoke(HttpContext context)
{
_logger.LogInformation("Handling request: " + context.Request.Path);
await _next.Invoke(context);
_logger.LogInformation("Finished handling request.");
}
}
public static class RequestLoggerExtensions
{
public static IApplicationBuilder UseRequestLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestLoggerMiddleware>();
}
}
public void ConfigureLogMiddleware(IApplicationBuilder app,
ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information); app.UseRequestLogger(); app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
}
------------------------------------------------------------------------------------------------------- Working with Static Files public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build(); host.Run();
} //*http://<app>/StaticFiles/test.png*//
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
}); -----------Enabling directory browsing--------------------
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
}); app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
-----------Enabling directory browsing-------------------- } public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
} -------Serving a default document-----------
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
} public void Configure(IApplicationBuilder app)
{
// Serve my app-specific default file, if present.
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
}
****************************************************************************************************** UseFileServer:combines the functionality of UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser. app.UseFileServer(enableDirectoryBrowsing: true); public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles"),
EnableDirectoryBrowsing = true
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
} http://<app>/StaticFiles/test.png MyStaticFiles/test.png
http://<app>/StaticFiles MyStaticFiles/default.html ***************************************************************************************************** FileExtensionContentTypeProvider: public void Configure(IApplicationBuilder app)
{
// Set up custom content types -associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4"); app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages"),
ContentTypeProvider = provider
}); app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
} Non-standard content types:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
});
}
DotNETCore 学习笔记 Startup、中间件、静态文件的更多相关文章
- (学习笔记)laravel 中间件
(学习笔记)laravel 中间件 laravel的请求在进入逻辑处理之前会通过http中间件进行处理. 也就是说http请求的逻辑是这样的: 建立中间件 首先,通过Artisan命令建立一个中间件. ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- java 学习笔记之 流、文件的操作
ava 学习笔记之 流.文件的操作 对于一些基础的知识,这里不再过多的解释, 简单的文件查询过滤操作 package com.wfu.ch08; import java.io.File; import ...
- Django学习之十: staticfile 静态文件
目录 Django学习之十: staticfile 静态文件 理解阐述 静态文件 Django对静态文件的处理 其它方面 总结 Django学习之十: staticfile 静态文件 理解阐述 ...
- Flask 学习(四)静态文件
Flask 学习(四)静态文件 动态 web 应用也需要静态文件,一般是 CSS 和 JavaScript 文件.理想情况下你的服务器已经配置好提供静态文件的服务. 在开发过程中, Flask 也能做 ...
- Java NIO 学习笔记(四)----文件通道和网络通道
目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...
- DotNetCore学习-3.管道中间件
中间件是用于组成应用程序管道来处理请求和响应的组件.管道内的每个组件都可以选择是否将请求交给下一个组件,并在管道中调用下一个组件之前和之后执行一些操作. 请求委托被用来建立请求管道,并处理每一个HTT ...
- Asp .Net core 2 学习笔记(2) —— 中间件
这个系列的初衷是便于自己总结与回顾,把笔记本上面的东西转移到这里,态度不由得谨慎许多,下面是我参考的资源: ASP.NET Core 中文文档目录 官方文档 记在这里的东西我会不断的完善丰满,对于文章 ...
- java jvm学习笔记三(class文件检验器)
欢迎装载请说明出处:http://blog.csdn.net/yfqnihao 前面的学习我们知道了class文件被类装载器所装载,但是在装载class文件之前或之后,class文件实际上还需要被校验 ...
随机推荐
- PLC状态机编程第二篇-负载均衡
控制任务 大家好,今天我们用状态机描述稍复杂的实例,同时用LAD和ST语言写状态机.我们的控制任务如下: 真空泵A和真空泵B, 按下启动按钮后, 泵A启动, 3秒后泵B也启动, 此时泵A仍运行, 当容 ...
- python之微信好友统计信息
需要安装库:wxpy 代码如下: from wxpy import Bot,Tuling,embed,ensure_one bot = Bot(cache_path=True) #获取好友信息 bot ...
- 笔记-falsk-入门-1
笔记-falsk-入门-1 1. 前言 有几个概念需要解释下,WSGI,JINJA2,WERKZEUG Flask是典型的微框架,作为Web框架来说,它仅保留了核心功能:请求响应处理和模板渲 ...
- talent-aio源码阅读小记(二)
我们上一篇提到了talent-aio的四类Task:DecodeRunnable.HandlerRunnable.SendRunnable.CloseRunnable,并且分析了这些task的基类Ab ...
- PHP.28-TP框架商城应用实例-后台5-多表操作-商品表与品牌表
表与表之间的关系:1:1 1:多 多:多 功能需求决定表关系 此处的表关系为:品牌表:商品表=1:多 1.首先在表结构上关联,在多的表(商品表)添加一个字段,关联一的表(品牌表)的ID(主键) 添加字 ...
- 15,redis基础学习
redis Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件 yum安装redis 1.yum安装 #前提得配置好阿里云yum源,epel源 #查看 ...
- (C)spring boot读取自定义配置文件时乱码解决办法
这是入门的第三天了,从简单的hello spring开始,已经慢慢接近web的样子.接下来当然是读取简单的对象属性了. 于是按照网上各位大神教的,简单写了个对象book,如上一篇(B),其他配置不需要 ...
- runloop的mode作用是什么?
用来控制一些特殊操作只能在指定模式下运行,一般可以通过指定操作的运行mode来控制执行时机,以提高用户体验 系统默认注册了5个Mode kCFRunLoopDefaultMode:App的默认Mode ...
- 《Cracking the Coding Interview》——第5章:位操作——题目5
2014-03-19 06:22 题目:将整数A变成整数B,每次只能变一个二进制位,要变多少次呢. 解法:异或,然后求‘1’的个数. 代码: // 5.5 Determine the number o ...
- USACO Section2.2 Party Lamps 解题报告 【icedream61】
lamps解题报告------------------------------------------------------------------------------------------- ...