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、中间件、静态文件的更多相关文章

  1. (学习笔记)laravel 中间件

    (学习笔记)laravel 中间件 laravel的请求在进入逻辑处理之前会通过http中间件进行处理. 也就是说http请求的逻辑是这样的: 建立中间件 首先,通过Artisan命令建立一个中间件. ...

  2. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  3. java 学习笔记之 流、文件的操作

    ava 学习笔记之 流.文件的操作 对于一些基础的知识,这里不再过多的解释, 简单的文件查询过滤操作 package com.wfu.ch08; import java.io.File; import ...

  4. Django学习之十: staticfile 静态文件

    目录 Django学习之十: staticfile 静态文件 理解阐述 静态文件 Django对静态文件的处理 其它方面 总结 Django学习之十: staticfile 静态文件 理解阐述     ...

  5. Flask 学习(四)静态文件

    Flask 学习(四)静态文件 动态 web 应用也需要静态文件,一般是 CSS 和 JavaScript 文件.理想情况下你的服务器已经配置好提供静态文件的服务. 在开发过程中, Flask 也能做 ...

  6. Java NIO 学习笔记(四)----文件通道和网络通道

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  7. DotNetCore学习-3.管道中间件

    中间件是用于组成应用程序管道来处理请求和响应的组件.管道内的每个组件都可以选择是否将请求交给下一个组件,并在管道中调用下一个组件之前和之后执行一些操作. 请求委托被用来建立请求管道,并处理每一个HTT ...

  8. Asp .Net core 2 学习笔记(2) —— 中间件

    这个系列的初衷是便于自己总结与回顾,把笔记本上面的东西转移到这里,态度不由得谨慎许多,下面是我参考的资源: ASP.NET Core 中文文档目录 官方文档 记在这里的东西我会不断的完善丰满,对于文章 ...

  9. java jvm学习笔记三(class文件检验器)

    欢迎装载请说明出处:http://blog.csdn.net/yfqnihao 前面的学习我们知道了class文件被类装载器所装载,但是在装载class文件之前或之后,class文件实际上还需要被校验 ...

随机推荐

  1. DSP资源分享贴

    DSP资源分享 [2017.5.16 更新] 分享资源共同学习.以前的资源很多人都说用不了了,我会陆续补充,逐步完善.这里不单单分享DSP的,设计基础的,还有其他的电子相关的比较好的资源吧主都和您分享 ...

  2. 学习python第十六天,正则表达式

    正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配.采取动态模糊的匹配,最大的应用是爬虫. re 模块使 Python 语言拥有全部的正则表达式功能. compile 函 ...

  3. 模块pandas

    python之pandas简单介绍及使用(一) https://www.cnblogs.com/misswangxing/p/7903595.html

  4. Aizu:2224-Save your cats

    Save your cats Time limit 8000 ms Memory limit 131072 kB Problem Description Nicholas Y. Alford was ...

  5. python向多个邮箱发邮件--注意接收是垃圾邮件

    群发邮件注意:三处标红的地方 # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from emai ...

  6. 使用windows live writer写cnblog-1 安装wlr

    Writer:在本地编辑有声在色的博客内容,发布到你的网络博客!   离线安装文件下载地址:http://dx1.itopdog.cn/soft/wlsetup-all.rar 下了好几个离线版本的, ...

  7. 直接选择排序&堆排序

    1.什么是直接选择排序? 直接选择排序(Straight Select Sort)是一种简单的排序方法,它的基本思想是:通过n-i次关键字之间的比较,从n-i+1个记录中选出关键字最小的记录,并和第i ...

  8. Java学习笔记17---成员方法的重载与重写

    重载是指,一个类中定义了一个成员方法后,通过修改参数个数.参数类型或参数顺序,重新实现该方法,则这两个方法互为对方的重载方法. 重写是指,子类重新实现父类的成员方法. 重载后的方法,与原方法相比: ( ...

  9. Java - 收藏集 -

    Java - 收藏集 -   Java 基础思维导图,让 Java 不再难懂 - 工具资源 - 掘金思维导图的好处 最近看了一些文章的思维导图,发现思维导图真是个强大的工具.了解了思维导图的作用之后, ...

  10. 树莓派Raspberry Pi 3安装步骤

    一.需要的硬件 1.Raspberry Pi 3(Model B+)树莓派.购买>https://item.jd.com/29225467867.html 2.输出5V/2A的电源 3.SD卡( ...