小编Xin*_*ng 的帖子

ASP.NET web api - 设置自定义IIdentity或IPrincipal

在我们的asp.net mvc/web api项目中,我们希望使用自定义授权AuthorizeAttribute.我们注意到有两种不同的AuthorizeAttribute,一种是System.Web.MVC用于MVC的System.Net.Http命名空间,另一种是用于web api的命名空间.

它适用于MVC,我们的代码如下:

public class MyPrincipal : IPrincipal
{
    //some custom properties
    public bool IsValid()
    {
        //custom authentication logic
    }

    private IIdentity identity;
    public IIdentity Identity
    {
        get { return this.identity; }
    }

    public bool IsInRole(string role)
    {
        return true;
    }
}

//override AuthorizeCore
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        MyPrincipal user = new MyPrincipal();

        if (user.isValid())
        {
            httpContext.User = user;
        }
        else
        { …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc asp.net-web-api

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

asp.net-mvc ×1

asp.net-web-api ×1