Asp Net核心授权
问题描述:
问题:只要普通用户尝试访问只能由管理员访问的页面,用户总是被重定向到登录而不是访问被拒绝的页面。Asp Net核心授权
问题:每当用户访问受限制的页面时,普通用户如何看到拒绝访问页面?
控制器:
[Authorize(Roles = "Administrator")]
public class AdminOnlyController: Controller{
}
Startup.cs
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "FirstCookieAuthentication",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AccessDeniedPath = new PathString("/Forbidden/"),
LoginPath = new PathString("/Conotroller/Login"),
});
答
拒绝访问仅仅是一个状态代码一样没有找到,内部错误等要管理状态代码,你可以使用中间件“app.UseStatusCodePages”。
代码:
if (env.IsDevelopment())
{
// see something more here
}
else
{
app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");
}
然后里面StatusCodeController,打造您提供的路线,前相匹配的操作结果:
[HttpGet("/StatusCode/{statusCode}")]
public IActionResult Index(int statusCode)
{
string statusmessage = "";
switch (statusCode)
{
case 400:
statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax";
break;
case 403:
statusmessage = "Forbidden";
break;
//all codes here...
default:
statusmessage = "That’s odd... Something we didn't expect happened";
break;
}
// return appropriate view
// or same view with different message, eg from ViewBag
}
+0
uhmm我检查了响应状态码,它总是返回200即使我作为普通用户访问受限制的页面。 –
答
我所做的是创建一个实现IActionFilter接口和一个自定义属性继承Attribute类。所以基本上我把我的代码放在On Action Executing Method中。不过,我也读过this关于不创建自定义属性的线程。但是我没有阅读评论部分的全部讨论。无论如何,这适用于我的情况。
请参阅更新 –