You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core 1.1中程序化验证用户对控制器方法的授权?

Great question—this is exactly the kind of scenario where leaning on your existing authorization system is the right move, instead of duplicating role-checking logic and risking mismatches later. Here's how you can do this cleanly in ASP.NET Core 1.1:

The Core Idea: Reuse the Authorization Middleware's Logic

Instead of querying AD groups directly, you can use ASP.NET Core's built-in IAuthorizationService to check if the current user meets the authorization requirements defined on your DeleteItem action. This way, any changes to the [Authorize] attribute will automatically reflect in the UI without extra work.

Step-by-Step Implementation

1. Inject Required Services

First, you'll need two services:

  • IAuthorizationService: Handles evaluating authorization rules.
  • IActionDescriptorCollectionProvider: Lets you look up metadata about your controller actions (including their authorization attributes).

You can inject these into your controller or directly into your view. Here's how to do it in a controller:

private readonly IAuthorizationService _authorizationService;
private readonly IActionDescriptorCollectionProvider _actionDescriptorProvider;

public ItemsController(IAuthorizationService authorizationService, 
                       IActionDescriptorCollectionProvider actionDescriptorProvider)
{
    _authorizationService = authorizationService;
    _actionDescriptorProvider = actionDescriptorProvider;
}

2. Check Authorization for the DeleteItem Action

In your action method (e.g., the one rendering the list view), fetch the metadata for DeleteItem and use IAuthorizationService to check access:

public async Task<IActionResult> Index()
{
    // Locate the DeleteItem action's metadata
    var deleteAction = _actionDescriptorProvider.ActionDescriptors.Items
        .FirstOrDefault(a => 
            a.RouteValues["controller"] == "Items" && 
            a.RouteValues["action"] == "DeleteItem");

    // Check if the current user is authorized to access this action
    var authResult = await _authorizationService.AuthorizeAsync(User, deleteAction, null);

    // Pass the result to the view
    ViewData["CanDeleteItems"] = authResult.Succeeded;
    return View();
}

3. Control UI Element Visibility

In your view, use the ViewData value to show/hide the red叉 button:

@foreach (var item in Model.Items)
{
    <div class="item-row">
        <!-- Other item details -->
        @if ((bool)ViewData["CanDeleteItems"])
        {
            <button class="delete-btn" data-item-id="@item.Id">❌</button>
        }
    </div>
}

Alternative: Check Directly in the View

If you prefer, you can inject the services directly into the view and perform the check there (just make sure to handle async properly):

@inject IAuthorizationService AuthorizationService
@inject IActionDescriptorCollectionProvider ActionDescriptorProvider

@{
    var deleteAction = ActionDescriptorProvider.ActionDescriptors.Items
        .FirstOrDefault(a => 
            a.RouteValues["controller"] == "Items" && 
            a.RouteValues["action"] == "DeleteItem");
    var canDelete = await AuthorizationService.AuthorizeAsync(User, deleteAction, null);
}

@foreach (var item in Model.Items)
{
    <div class="item-row">
        <!-- Other item details -->
        @if (canDelete.Succeeded)
        {
            <button class="delete-btn" data-item-id="@item.Id">❌</button>
        }
    </div>
}

Why This Works

  • No Duplication: You're using the exact same authorization logic that protects the DeleteItem action—any changes to the [Authorize(Roles)] attribute will automatically update the UI check.
  • DRY Compliance: Avoids repeating AD group checks in both the controller and UI, reducing the chance of bugs when roles change.
  • Framework-Native: Leverages ASP.NET Core's built-in authorization system, so you don't have to roll custom logic.

内容的提问来源于stack exchange,提问作者Larry Lustig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:26:50