ASP.NET Core 2.0에서 라우팅을 실험하고 있습니다. 나는 (간단한 단위 테스트의 경우) System.DateTime.UtcNow
기능을 래핑하는 클래스ASP.Net Core RouteBuilder 및 종속성 주입
public interface IDateTimeWrapper
{
DateTime UtcNow();
}
public sealed class DateTimeWrapper : IDateTimeWrapper
{
public DateTime UtcNow()
{
return DateTime.UtcNow;
}
}
이이 HttpResponse
public class WhatIsTheTimeHandler
{
private readonly IDateTimeWrapper _dateTimeWrapper;
public WhatIsTheTimeHandler(
IDateTimeWrapper dateTimeWrapper)
{
this._dateTimeWrapper = dateTimeWrapper;
}
public async Task Execute(Microsoft.AspNetCore.Http.HttpContext httpContext)
{
httpContext.Response.StatusCode = 200;
await httpContext.Response.WriteAsync(this._dateTimeWrapper.UtcNow().ToString());
}
}
에
DateTimeWrapper
의 결과를 기록하는 하나의 방법
Execute
가있는 클래스에 의해 사용이
에서 에있는 모든 요청을 으로 처리하려면 WhatIsTheTimeHandler
으로 처리해야합니다 (!!! 참조).
public sealed class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
builder.SetBasePath(env.ContentRootPath);
builder.AddJsonFile("appsettings.json", false, true);
// we must lowercase the json file path due to linux file name case sensitivity
builder.AddJsonFile($"appsettings.{env.EnvironmentName.ToLower()}.json", false, true);
builder.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddScoped<IDateTimeWrapper, DateTimeWrapper>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var routeBuilder = new Microsoft.AspNetCore.Routing.RouteBuilder(app);
// !!!
// I want to do something like
// routeBuilder.MapGet("whatisthetime", WhatIsTheTimeHandler.Execute);
var routes = routeBuilder.Build();
app.UseRouter(routes);
}
}
WhatIsTheTimeHandler.Execute
이 인스턴스 메서드이기 때문에 위의 동작을 수행 할 수 없습니다. 나는. 오류 :
An object reference is required for the non-static field, method or property 'WhatIsTheTimeHandler.Execute(HttpContext)' Cannot access non-static method in static context).
나는 static
나는이 _dateTimeWrapper
인스턴스 멤버를 사용할 수 없습니다 확인합니다.
아이디어가 있으십니까?
는 미들웨어를 만들 HTTPS
그러나, 현재의 솔루션 작품을 만들기 위해 당신은 서비스로 처리기를 추가해야합니다 : //docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware? tabs = aspnetcore2x 또한 DI 허용 – Nkosi
'WhatIsTheTimeHandler'가 왜 '컨트롤러'가 아닌지 궁금하십니까? –
@CamiloTerevinto는이 질문에 더 많은 생각을 할애하여 매우 중요한 포인트를 만듭니다. – Nkosi