在我正在处理的一个 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
}
}