【问题标题】:Why to create a custom principal interface when you want to create a Custom Principal in Asp.net MVC?当你想在 Asp.net MVC 中创建自定义主体时,为什么要创建自定义主体接口?
【发布时间】:2015-08-29 12:58:19
【问题描述】:

最近我搜索了如何创建自定义主体,我得到了答案,但有一件事我不明白,我在堆栈溢出时找到了这个解决方案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
namespace workflow.Authorize
{
    interface ICustomPrincipal : IPrincipal
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public class CustomPrincipal : ICustomPrincipal
    {

        public IIdentity Identity { get; private set; }
        public bool IsInRole(string role) {

            if(this.Roles.Contains(role))
             return true; 
            else
                return false;
        }

        public CustomPrincipal(string email)
        {
            this.Identity = new GenericIdentity(email);
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Roles { get; set; }
    }

    public class CustomPrincipalSerializeModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Roles { get; set; }
    }

}

但我不明白的是为什么开发人员创建了 ICustomPrincipal 接口并强制 CustomPrincipal 继承它,为什么 CustomPrincipal 类不直接从 IPrincipal 接口继承

【问题讨论】:

    标签: asp.net-mvc iprincipal principal custom-authentication


    【解决方案1】:

    对我来说,如果您需要强制用户覆盖其他属性和方法,那么您必须创建一个自定义界面。

    开发人员创建了一个自定义界面并添加了新属性,例如 FirstName 属性和 LastName 属性,以强制您应用它们。

    查看here,您会发现 Iprincipal 接口的唯一属性是 identity 属性,这对您来说还不够。

    我希望这可以帮助您理解为什么开发人员有时会创建一些自定义界面。

    【讨论】: