C# 主许可请求授权失败

C# 主许可请求授权失败,c#,.net,wcf,C#,.net,Wcf,我有一个服务,其中一些方法具有PrincipalPermissionAttribute。如果主体检查失败,我想请求身份验证。 例如: [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")] public string GetData() 若调用用户是管理员,则服务应返回数据。 若调用用户不是管理员,则服务应请求身份验证,若身份验证失败,则服务应返回401响应。我怎样才能做到这一点呢?好的,我已经用一个助手类做到了

我有一个服务,其中一些方法具有PrincipalPermissionAttribute。如果主体检查失败,我想请求身份验证。 例如:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetData()
若调用用户是管理员,则服务应返回数据。
若调用用户不是管理员,则服务应请求身份验证,若身份验证失败,则服务应返回401响应。我怎样才能做到这一点呢?

好的,我已经用一个助手类做到了:

internal static class UserPermissions
{
    public static bool CheckRole(Role role)
    {
        try {
            var p = new PrincipalPermission(null, role.ToString());
            p.Demand();
        }
        catch (SecurityException) {
            return false;
        }
        return true;
    }

    public static void AssertRole(Role role)
    {
        if (!CheckRole(role)) {
            throw new WebFaultException(HttpStatusCode.Unauthorized);
        }
    }
}

public enum Role
{
    Administrator,
    Customer
}
使用这种用法:

public class CustomerService : ICustomerService
{
        public List<Order> GetOrders()
        {
            UserPermissions.AssertRole(Role.Customer);
            // Code to get orders.
        }
}
公共类CustomerService:ICCustomerService
{
公共列表GetOrders()
{
UserPermissions.AssertRole(Role.Customer);
//获取订单的代码。
}
}
所以,我放弃了乒乓认证请求的想法,只返回401错误