4

在我正在处理的一个 MVC3 项目中,我们试图将当前在控制器中的许多逻辑移动到服务层中,并将其公开为 WCF 中的 REST 服务。

因此,在我们的 Global.asax 中,我们创建了一个服务路由,如下所示:

RouteTable.Routes.Add(new ServiceRoute
    ("Exampleservice", new WebServiceHostFactory(), typeof(ExampleService)));

我们的控制器访问服务是这样的:

public class ExampleController : Controller {
    private IExampleService service;

    public ExampleController() {
        this.service = new ExampleService();
    } 

    public ActionResult Index() {
         var results = service.GetAll();
         return View(results);
    }
}

这里的要点是我们直接使用服务类(不使用 HttpClient 通过网络发出请求)。

我们的网站使用 Windows 身份验证(它是一个 Intranet 网站),我们希望保持这种方式。我的问题是,有没有一种方法可以让我在服务类中获取用户的身份,这既适用于控制器使用服务的方式,也适用于 WCF 使用服务的方式?

例如:

[ServiceContract]
public interface IExampleService
{
    [WebGet(UriTemplate = "/")]
    List<Results> GetAll();
}

public class ExampleService : IExampleService
{
     List<Results> GetAll() {
         // Get User Name Here
         // In ASP.Net I would use User.Identity.Name
         // If I was just worrying about the the REST service I would use
         // ServiceSecurityContext.Current.WindowsIdentity.Name
     }
}
4

2 回答 2

1

@Ryand.Johnson 建议的指令是正确的。这里的重点是控制器不会向 Web 服务发送任何凭据,因为它以 asp.net 用户身份而不是当前登录用户的身份运行。将身份传递给代理的唯一方法是通过以下方式将对 Web 服务的调用嵌入到模拟上下文中:

using (WindowsImpersonationContext impersonatedUser = (User.Identity as System.Security.Principal.WindowsIdentity).Impersonate()){ 
     //your proxy call here  }

如果仍然以这种方式获得 null,则必须手动将默认凭据设置为代理

于 2012-06-17T18:03:59.810 回答
0

是的,在服务安全上下文中......

OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name

于 2012-06-06T20:21:26.773 回答