【发布时间】:2019-10-07 14:11:53
【问题描述】:
我目前正在测试一个 asp.net core 3 blazor 服务器端应用程序。我在 f# 中构建了一个中间件扩展,并在 Startup 类的 Configure 方法中从 c# 调用它。它似乎最初尝试重定向,因为调用了正确的 url,但我收到一个错误页面,指出该页面未正确重定向。我在这里想念什么。
F#:
type CheckMaintenanceStatusMiddleWare(next : RequestDelegate) =
let _next = next
member this.InvokeAsync(context : HttpContext) =
let statusCheck = true
if statusCheck
then
Task.Run(fun arg -> context.Response.Redirect("/Maintenance"))
else
_next.Invoke(context)
[<Extension>]
type CheckMaintenanceStatusMiddleWareExtensions() =
[<Extension>]
static member inline UseCheckMaintenanceStatus(builder : IApplicationBuilder) =
builder.UseMiddleware<CheckMaintenanceStatusMiddleWare>()
C#
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCheckMaintenanceStatus();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
剃须刀组件:
@page "/Maintenance"
<h3>Maintenance</h3>
@code {
}
【问题讨论】:
-
好像你的代码让浏览器一直重定向?
-
如果是这种情况,请检查当前路径是否为
/Maintenance以避免重定向循环:if statusCheck && context.Request.Path.Value <> "/Maintenance" then -
注意你不需要
let _next = next,你可以直接使用next。另外,通过在线程池上调度来创建任务成本很高(出于各种原因),考虑使用Task.FromResult -
@itminus 你的建议奏效了。您能否将此作为答案提交,以便我接受。您还可以在答案中解释在这种情况下如何创建循环。
-
@CaringDev 你能更详细地解释一下如何做到这一点。我在中间件构造的文档中没有看到任何这样的例子,关于我的 if 语句,我只是试图与 next.Invoke 保持一致,其中返回类型 Task。
标签: c# asp.net asp.net-core f# asp.net-core-3.0