ASP.NET MVC:无法访问静态方法

本文关键字:访问 静态方法 NET MVC ASP | 更新日期: 2023-09-27 18:37:05

我在控制器文件夹中创建了一个名为Utils的类。但是,找不到和访问其静态方法。以下是声明:

using ProjectManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.Identity;
using System.Web.Security;
        namespace ProjectManager.Controllers
        {
            public static class Utils
            {
                public static bool isInRole(IPrincipal User, string roleName, ApplicationDbContext dbContext)
                {
                    try
                    {
                        var currentUser = (from user in dbContext.Users
                                           where user.Id == User.Identity.GetUserId()
                                           select user).First();
                        RolePrincipal r = (RolePrincipal)User;
                        string[] rolesArray = r.GetRoles();
                        if (rolesArray.Contains(roleName))
                            return true;
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                    return false;
                }
            }
        }

ASP.NET MVC:无法访问静态方法

如果该类在多个页面上使用,请将命名空间添加到 Views 文件夹中的 web.config

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="ProjectManager.Controllers" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
无论你

想在哪里使用它,VSB,你都需要添加:

using ProjectManager.Controllers;

到班级的顶端,或者:

@using ProjectManager.Models

在剃刀视图中。

编辑:正如@Martin Staufcik非常指出的那样,它可以添加到视图文件夹web.config的命名空间部分,以便在该文件夹中的视图中访问,而无需在每个视图中都有@using。

但是,您仍然必须为每个后端类添加一个使用。