简体   繁体   English

Blazor 相当于 OnActionExecuting?

[英]Blazor equivalent to OnActionExecuting?

In my MVC controllers, I would overload the OnActionExecuting method to check for security rights accessibility.在我的 MVC 控制器中,我将重载OnActionExecuting方法来检查安全权限可访问性。 Is there an equivalent to this behavior in Blazor serverside when routing to razor pages without controllers?在没有控制器的情况下路由到 razor 页面时,Blazor 服务器端是否存在与此行为等效的行为?

public override void OnActionExecuting(ActionExecutingContext context)
{
    if (!context.IsAuthorized(out string message))
        context.Result = StatusCode((int)HttpStatusCode.Unauthorized, 
message);
    base.OnActionExecuting(context);
}

Although I am not sure if this is the best way to solve this, (I would love to know if it is), I have found a workaround and hopefully this can help someone else as well尽管我不确定这是否是解决此问题的最佳方法,(我很想知道是否是),但我找到了一种解决方法,希望这也可以对其他人有所帮助

I intercepted the Found method of the Router as so:我这样截获了RouterFound方法:

@inject IUserContext User

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        @if (routeData.IsAuthorizedFor(User, out string message))
        {
            <RouteView RouteData="@routeData" DefaultLayout="typeof(MainLayout)" />
        }
        else
        {
            <LayoutView Layout="typeof(MainLayout)">
                <p>@message</p>
            </LayoutView>
        }
    </Found>
    <NotFound>
        <LayoutView Layout="typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

The reason I don't think this is optimal is because this doesn't seem like the type of code that should go in a razor file.我认为这不是最佳的原因是因为这看起来不像 razor 文件中应该 go 的代码类型。 The Router methods were not virtual either, because I did consider creating my own router type inheriting from that one. Router方法也不是虚拟的,因为我确实考虑过创建自己的路由器类型,继承自那个。

This works for me in Blazor .NET 5 from the base class (ie the.cs file, not the.razor file. I didn't try from.razor file). This works for me in Blazor .NET 5 from the base class (ie the.cs file, not the.razor file. I didn't try from.razor file).

using Microsoft.AspNetCore.Components;

namespace YourProjectName.Pages
{
    public class YourRazorFileName: ComponentBase
    {
        protected override void OnInitialized()
        {
            base.OnInitialized();
           //Insert things you want to run on initialize here
        }
    }
}

Other similar methods: OnAfterRender, OnParametersSet.其他类似方法:OnAfterRender、OnParametersSet。 See https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.componentbase.onafterrender?view=aspnetcore-5.0请参阅https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.componentbase.onafterrender?view=aspnetcore-5.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM