简体   繁体   中英

Blazor equivalent to OnActionExecuting?

In my MVC controllers, I would overload the OnActionExecuting method to check for security rights accessibility. Is there an equivalent to this behavior in Blazor serverside when routing to razor pages without controllers?

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:

@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. The Router methods were not virtual either, because I did consider creating my own router type inheriting from that one.

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. See https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.componentbase.onafterrender?view=aspnetcore-5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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