在我正在处理的 MVC3 项目中,我们试图将当前在 Controller 中的许多逻辑移动到服务层中,并将其作为 WCF 中的 REST 服务公开。
所以在我们的 Global.asax 中,我们创建了一个服务路由,如下所示:
RouteTable.Routes.Add(new ServiceRoute
("Exampleservice", new WebServiceHostFactory(), typeof(ExampleService)));
和我们的 Controller 访问服务是这样的:
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 站点),我们希望保持这种方式。我的问题是,有没有一种方法可以让我在服务类中获取用户的身份,它既适用于我们让 Controller 使用服务的方式,也适用于 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
}
}
最佳答案
@Ryand.Johnson 建议的指令是正确的。这里的要点是 Controller 不会向 Web 服务发送任何凭据,因为它在 asp.net 用户身份下运行,而不是当前登录用户的身份。将身份传递给代理的唯一方法是通过以下方式在模拟上下文中嵌入对 Web 服务的调用:
using (WindowsImpersonationContext impersonatedUser = (User.Identity as System.Security.Principal.WindowsIdentity).Impersonate()){
//your proxy call here }
如果仍然以这种方式获得 null,则必须手动设置代理的默认凭据
关于asp.net-mvc-3 - 使用 Windows 身份验证获取 WCF 中当前交互用户的用户名,包括 Rest Endpoint 和 MVC3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10921253/