如果我理解你的问题,你想的路线,只是只授权特定的路径?
如果是这样,你可以使用路由作为的WebAPI 2
的一部分内WebAPIConfig.cs
您的API控制器中添加以下配置
public static void Register(HttpConfiguration config)
{
//Enable attribute routing
config.MapHttpAttributeRoutes();
//... additional configuraitons
}
然后情况下,你可以设定的路线独立于违约并添加任何你需要的属性:
[Route("apiname/authroizedLogin")]
[Authorize(Roles="admin")]
public void IHttpActionResult(string username, stringpassword)
{
try
{
dosomething...
return Ok(somecontext);
}
catch(exception e)
{
return BadResponse(e.message);
}
}
Here is a link with more information on routes in WebAPI 2
编辑
关于访问角色。这取决于你的实现。我个人不喜欢使用global.asx,因为它会更频繁地创建数据库请求。我需要更多关于您的实施的信息才能提出真正的建议。但是,这里有几个选项。如果您使用claims based authentication,则该角色可以是声明的一部分,并将作为http上下文/请求的一部分传递给API。如果你不使用的权利要求另一选择是将生成一个FormsAuthenticaitonTicket这可以被加密,一旦用户被认证为一个cookie存储
public long RoleId
{
get
{
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
string id = identity.Claims.Where(c => c.Type == "http://myschema.com/app/claims/roleid")
.Select(c => c.Value).SingleOrDefault();
//return 0 if no claim is located
return (!String.IsNullOrEmpty(id)) ? Convert.ToInt32(id) : 0;
}
set
{
_userId = value;
}
}
:从这里可以推导出身份。
我从来没有见过/以这种方式思考,我的做法似乎更容易。但我仍然需要制作自己的角色映射,我不知道在哪里@Landro – 2015-02-24 14:30:49
我已经添加了一些可能有所帮助的附加信息 – rlcrews 2015-02-24 15:47:10
非常感谢!是的,我正在看如何实现类似的东西,还有FormsAuthTicket! – 2015-02-24 15:49:47