簡體   English   中英

Blazor 相當於 OnActionExecuting?

[英]Blazor equivalent to OnActionExecuting?

在我的 MVC 控制器中,我將重載OnActionExecuting方法來檢查安全權限可訪問性。 在沒有控制器的情況下路由到 razor 頁面時,Blazor 服務器端是否存在與此行為等效的行為?

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

盡管我不確定這是否是解決此問題的最佳方法,(我很想知道是否是),但我找到了一種解決方法,希望這也可以對其他人有所幫助

我這樣截獲了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>

我認為這不是最佳的原因是因為這看起來不像 razor 文件中應該 go 的代碼類型。 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).

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
        }
    }
}

其他類似方法:OnAfterRender、OnParametersSet。 請參閱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