我使用Visual Studio 2015创建了一个新的Web API项目,运行良好。然后我添加了以下步骤。
为角色,roleMembers创建表,并首先使用代码创建所有数据访问代码
创建一个继承RoleProvider的自定义角色提供程序类
更新web.config文件以使用自定义角色提示程序
使用[授权(角色=" TestRole"]
详细说明:
创建了用于存储角色和成员资格的以下表格。
create table Roles (Id int primary key, Role nvarchar(50) not null)
create TABLE RoleMember (RoleId int references Roles(Id), userId varchar(50) not null primary key(RoleId, userId))
自定义角色提供程序代码
namespace webapi.Models
{
public class MyRoleProvider : RoleProvider
{
public override string ApplicationName { .... }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { .... }
public override void CreateRole(string roleName) { .... }
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { .... }
public override string[] FindUsersInRole(string roleName, string usernameToMatch) { .... }
public override string[] GetAllRoles() { .... }
public override string[] GetRolesForUser(string username)
{
using (var db = new MyContext()) // break point set here
{
var roles = from rm in db.RoleMembers
from r in db.Roles
where r.Id == rm.RoleId && rm.userId == username
select r.Role;
if (roles!=null)
{
return roles.ToArray();
}
else
{
return new string[] { };
}
}
}
public override string[] GetUsersInRole(string roleName) { .... }
public override bool IsUserInRole(string username, string roleName)
{
using (var db = new MyContext()) // Break point set here
{
var roles = from rm in db.RoleMembers
from r in db.Roles
where r.Id == rm.RoleId && rm.userId == username
select r.Role;
if (roles!=null)
{
return roles.Any(r=> r.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
}
else
{
return false;
}
}
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { .... }
public override bool RoleExists(string roleName) { .... }
}
}
web.config文件已更新。
<system.web>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<roleManager cacheRolesInCookie="true" defaultProvider="MyRoleProvider" enabled="true">
<providers>
<clear/>
<add name="MyRoleProvider" type="webapi.Models.MyRoleProvider"/>
</providers>
</roleManager>
</system.web>
然后控制器被装饰。
namespace webapi.Controllers
{
[Authorize(Roles = "TestRole")] // The web api call returns value before add this line
public class MyController : ApiController
{
然而,测试&#34; http://localhost:23151/api/MyController&#34;得到了&#34;的错误 此请求已被拒绝授权。 &#34;所以我在自定义角色提供程序中设置了断点。但调试时没有一个可以被击中?