Open JHinW opened 7 years ago
asp .net core run middleWare in functional way, see this.
use lamda to show above logic: context => action(context).
we still need a next delegate to call, so lamda should look like this: next => {action(context); next.invoke();}
private static IApplicationBuilder UseMiddlewareInterface(IApplicationBuilder app, Type middlewareType)
{
return app.Use(next /*this is next delegate*/=>
{
return async context =>
{
try
{
await middleware.InvokeAsync(context, next);
}
};
});
}
read code snippet
// this method will compose all middlewares which will make all delegate run in a single method.
public RequestDelegate Build()
{
RequestDelegate app = context =>
{
context.Response.StatusCode = 404;
return Task.CompletedTask;
};
foreach (var component in _components.Reverse())
{
app = component(app);
}
return app;
}
read code snippet
how [Ctrl+C] works when web console app is running
public static async Task RunAsync(this IWebHost host, CancellationToken token = default(CancellationToken))
{
// Wait for token shutdown if it can be canceled
if (token.CanBeCanceled)
{
await host.RunAsync(token, shutdownMessage: null);
return;
}
// If token cannot be canceled, attach Ctrl+C and SIGTERM shutdown
// add by me:
// ManualResetEventSlim only be setted when host.RunAsync is called
var done = new ManualResetEventSlim(false);
using (var cts = new CancellationTokenSource())
{
AttachCtrlcSigtermShutdown(cts, done, shutdownMessage: "Application is shutting down...");
await host.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down.");
done.Set();
}
}
when you need to debug above open source
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "dotnet",
"isShellCommand": true,
"args": [],
"tasks": [
{
"taskName": "build",
"args": [
"./samples/SampleStartups/SampleStartups.csproj"
],
"isBuildCommand": true,
"showOutput": "silent",
"problemMatcher": "$msCompile"
}
]
}
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceRoot}/samples/SampleStartups/bin/Debug/netcoreapp2.0/SampleStartups.dll",
"args": [],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceRoot}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http/Internal/ApplicationBuilder.cs