在 blazor 应用程序中,如果渲染模式设置为“服务器”,是否可以获得请求的路径?

R. *_*ats 3 c# httpcontext blazor

我创建了一个 Blazor 客户端应用程序,在该应用程序中,我有许多具有自定义要求和处理程序的授权策略。其中之一检查URL中请求的ID并检查登录用户是否可以查看该资源。

\n\n

例如,通过客户端,用户导航到https://localhost/resource/1f28e41c-bc75-44d6-9eef-d46b66b649c7 ,这是我的 API 上的资源。

\n\n

I\xe2\x80\x99m 使用以下代码查看请求路径:

\n\n
var httpContext = _httpContextAccessor.HttpContext;\nstring requestedPath = httpContext.Request.Path.ToString();\n
Run Code Online (Sandbox Code Playgroud)\n\n

这曾经有效,requestedPath 确实包含值 \xe2\x80\x9c1f28e41c-bc75-44d6-9eef-d46b66b649c7\xe2\x80\x9d

\n\n

但是,在 _Host.cshtml 中,我已将渲染模式从“ServerPrerendered”更改为“Server”。这是因为在页面调用期间代码在不同位置执行了两次。

\n\n

由于我更改了此设置,requestedPath 值始终为“/_blazor”。

\n\n

所以我想知道,在 blazor 应用程序中,如果渲染模式设置为“服务器”,是否可以获得请求的路径?

\n

Isa*_*aac 5

我创建了一个 Blazor 客户端应用程序

不,你没有。您的应用程序是 Blazor 服务器应用程序(也称为服务器端 Blazor 应用程序)。

由于您的应用程序是基于 WebSocket 连接的,而不是基于 HTTP 的,因此您不能也不应该尝试访问 HttpContext 对象。HttpContext 不存在于基于 SignalR 的应用程序中,例如您使用的应用程序(Blazor 服务器应用程序)。

以下代码片段创建一个名为 Profile 的 Razor 组件,其中包含一个名为 ID 的参数(路由值),您应将其传递给 IAuthorizationHandler

Profile.razor

@page "/profile"
@page "/profile/{id}"

 <AuthorizeView Policy="Place here the name of your policy" 
                                                Resource="@ID">
      <NotAuthorized>
        <h2 class="mt-5">You are not authorized to view this page</h2>
      </NotAuthorized>
      <Authorized>
        <div class="container my-profile">
            <h2>My Profile</h2>
            --- Place here all the content you want your user to view ----
        </div>
      </Authorized>
</AuthorizeView>

@code {

   [Parameter]
   public string ID { get; set; }
Run Code Online (Sandbox Code Playgroud)

}

请注意:配置文件 ID 通过 AuthorizeView.Resource 属性传递到您的处理程序方法

在处理程序方法中,您可以执行以下操作:

 public Task HandleAsync(AuthorizationHandlerContext context)
    {
        if (context == null) return Task.CompletedTask;

        // get the profile id from resource, passed in from the profile page 
        // component
        var resource = context.Resource?.ToString();
        var hasParsed = int.TryParse(resource, out int profileID);
        if (hasParsed)
        {
            // compare the requested profileID to the user's actual claim of 
            // profileID
            var isAuthorized = profileID == context.User.GetProfileIDClaim();
            -- --- I can't code blindly any more-----
        }

    }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助..