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文件实际上还需要被校验 ...
随机推荐
- JZOJ 3534. 【NOIP2013提高组day1】货车运输
Description A 国有 n 座城市,编号从 1 到 n,城市之间有 m 条双向道路.每一条道路对车辆都有重量限制,简称限重.现在有 q 辆货车在运输货物,司机们想知道每辆车在不超过车辆限重的 ...
- python3 练习题100例 (十九)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """练习十九:计算1-2+3...+99中除了88以外所有数的和" ...
- SQL Server 数据库内部版本号
数据库还原或版本升级出现版本错误时可参考 可以利用SQL语句查看本机数据库版本:select @@VERSION 如果你不确定是源数据库的版本,下面的映射表的SQL Server版本的内部版本号,以便 ...
- JVM——九大工具助你玩转Java性能优化
本文转载自 http://www.importnew.com/12324.html 本文由 ImportNew - 陈 晓舜 翻译自 idrsolutions.欢迎加入翻译小组.转载请参见文章末尾的要 ...
- 5,版本控制git --标签管理
打标签 像其他版本控制系统(VCS)一样,Git 可以给历史中的某一个提交打上标签,以示重要. 比较有代表性的是人们会使用这个功能来标记发布结点(v1.0 等等). 在本节中,你将会学习如何列出已有的 ...
- 4-linux基本命令
1. cd命令 cd 回当前用户 家目录 cd /home 进入home目录 (绝对路径) (相对路径) cd – 上一目录和当前目录来回切换(主要用于返回上一目录) cd . ...
- 关于 package.json 和 package-lock.json 文件说明
package.json 在 Node.js 中,模块是一个库或框架,也是一个 Node.js 项目.Node.js 项目遵循模块化的架构,当我们创建了一个 Node.js 项目,意味着创建了一个模块 ...
- React-router4简约教程
React-router4简约教程 教程 webEmmet 17年10月 React-router和React-router-dom的选择 很多刚使用react的同学在接触到react ...
- CSS 一些基础知识(优先级、行内元素的一些属性、font-size单位) 怎样不加载图片
CSS大小写不敏感 选择器优先级如下所示: 在属性后面使用 !important 会覆盖页面内任何位置定义的元素样式. 作为style属性写在元素内的样式 id选择器 类选择器 标签选择器 通配符选择 ...
- 《Cracking the Coding Interview》——第17章:普通题——题目8
2014-04-28 23:35 题目:最大子数组和问题. 解法:O(n)解法. 代码: // 17.8 Find the consecutive subarray with maximum sum ...