asp.net - 使用中间件 ASP.NET 进行依赖注入
问题描述
我有办法编写一些代码来使用中间件在屏幕上获取当前时间。我有下一节时间服务
public class TimeService
{
public TimeService()
{
Time = DateTime.Now.ToString("hh:mm:ss");
}
public string Time { get; }
}
和下一个 TimerMiddleware 类
public class TimerMiddleware
{
private readonly RequestDelegate _next;
TimeService _timeService;
public TimerMiddleware(RequestDelegate next, TimeService timeService)
{
_next = next;
_timeService = timeService;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.Value.ToLower() == "/time")
{
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync($"Current time: {_timeService?.Time}");
}
else
{
await _next.Invoke(context);
}
}
}
现在我的启动类看起来像这样:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<TimeService>();
}
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<TimerMiddleware>();
app.Run(async (context) =>
{
await context.Response.WriteAsync();
});
}
}
我应如何修改“启动”类中的“运行”方法以在屏幕上显示时间?
解决方案
推荐阅读
- asp.net-core - $(...).formSelect 不是函数
- typescript - 为什么 TypeScript 不能推断出相同对象类型的赋值?
- arrays - 在将一列复制到另一列之前是否可以制作 if/else ?
- java - 如何使用 java selenium chromedriver 单击图像/按钮
- excel - 如何更改纸张的打印方向?
- airflow - 防止气流回填作业
- javascript - React Hook "useContext" 在函数 "age" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数
- python - 每次我使用 Google Drive API 搜索并将它们存储在列表中时都会附加文件名?
- filtering - Spotfire - 按计算列中的值过滤表
- ios - 稍后使 HStack 中的项目可见/不可见