Ami*_*udi 4 c# asp.net asp.net-core
我创建了一个登录中间件,如果用户未经过身份验证,它将重定向到登录页面。
using FileManager.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FileManager.Middleware
{
public class LoginRequiredMiddleware
{
private readonly RequestDelegate _next;
public LoginRequiredMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
Console.WriteLine("Middleware");
User user = Models.User.getCurrentUser(httpContext);
if(user == null)
{
Console.WriteLine("Redirecting");
httpContext.Response.Redirect("/login/");
}
await _next.Invoke(httpContext);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将其添加到Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
app.UseMiddleware<LoginRequiredMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器
using FileManager.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FileManager.Controllers
{
public class DefaultController : Controller
{
[Route("")]
public IActionResult Index()
{
Console.WriteLine("Controller");
ExtraBag();
User user = ViewBag.User;
var files = user.files();
ViewBag.Files = files;
return View("Index");
}
public void ExtraBag()
{
ViewBag.User = Models.User.getCurrentUser(HttpContext);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
var files = user.files();=> System.NullReferenceException:“未将对象引用设置为对象的实例。”
因此,显然,当我未经身份验证时,我的中间件不会重定向,因此user保持为空并传递给控制器。
这是我通过调试得到的输出
Middleware
Security Warning: The negotiated TLS 1.0 is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.
Redirecting
Controller
Run Code Online (Sandbox Code Playgroud)
Noa*_*ahl 10
您的中间件需要提前返回而不调用next. return设置重定向后:
if (user == null && httpContext.Request.Path != "/login/")
{
Console.WriteLine("Redirecting");
httpContext.Response.Redirect("/login/");
return; // Return now with redirect response, don't fall through to next
}
await _next.Invoke(httpContext);
Run Code Online (Sandbox Code Playgroud)
Redirect本身不会导致该Invoke方法返回。
另请注意路径检查以防止重定向循环。
| 归档时间: |
|
| 查看次数: |
3662 次 |
| 最近记录: |