https://source.dot.net/#Microsoft.AspNetCore.Http/Builder/ApplicationBuilder.cs,132
public class ApplicationBuilder : IApplicationBuilder {
private readonly List<Func<RequestDelegate, RequestDelegate>> _components = new();
...
public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) {
_components.Add(middleware);
return this;
}
public RequestDelegate Build() {
RequestDelegate app = context => {
...
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
}
}
for (var c = _components.Count - 1; c >= 0; c--) {
app = _components[c](app);
}
return app;
}
如您所見,RequestDelegateapp將始終被執行,這意味著狀態碼將設定為 404,這完全沒有意義。對我來說,代碼應該是這樣的:
public RequestDelegate Build() {
RequestDelegate app = context => {
...
if (context.Response has not been set) { // pesudo code
context.Response.StatusCode = StatusCodes.Status404NotFound;
}
return Task.CompletedTask;
}
}
uj5u.com熱心網友回復:
此代碼假定您已經添加了端點中間件:https : //github.com/aspnet/Routing/blob/master/src/Microsoft.AspNetCore.Routing/EndpointMiddleware.cs
// If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened.
// This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware.
在端點中間件中:
public async Task Invoke(HttpContext httpContext)
{
var endpoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint?.RequestDelegate != null)
{
Log.ExecutingEndpoint(_logger, endpoint);
try
{
await endpoint.RequestDelegate(httpContext);
}
finally
{
Log.ExecutedEndpoint(_logger, endpoint);
}
return;
}
await _next(httpContext);
}
因此,您共享的代碼處理了端點的不存在,從而回傳 404。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406516.html
標籤:
上一篇:考慮到它們之間的依賴關系,我應該如何將我的專案發布為NuGet包?
下一篇:無法反序列化當前JSON物件C#
