2009-06-01 82 views
0

如何獲取請求者的域名或完整URL?獲取WCF請求的域名?

+0

您的意思是用於訪問服務的URL?客戶的身份? – 2009-06-02 18:07:50

+0

沒有客戶的引用域。 – DDiVita 2009-06-05 11:19:32

回答

3

我不知道,我明白你的問題,但如果你需要的Windows用戶進行調用服務操作的域名,使用此:

OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name 

這將返回「{域}\{用戶名}」。

試試這個,讓我知道你在想什麼(你可能會想這段代碼粘貼到一個MSTEST項目):

[TestClass] 
public class AlternativeCredentials 
{ 
    // Contracts 
    [ServiceContract] 
    interface IMyContract 
    { 
     [OperationContract] 
     string GetUserName(); 
    } 

    // Service 
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)] 
    class MyService : IMyContract 
    { 
     public string GetUserName() 
     { 
      return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; 
     } 
    } 

    // Client 
    class MyContractClient : ClientBase<IMyContract>, IMyContract 
    { 
     public MyContractClient() { } 
     public MyContractClient(Binding binding, string address) : 
      base(binding, new EndpointAddress(address)) { } 

     public string GetUserName() 
     { return Channel.GetUserName(); } 
    } 

    #region Host 
    static string address = "net.tcp://localhost:8001/" + Guid.NewGuid().ToString(); 
    static ServiceHost host; 

    [ClassInitialize()] 
    public static void MyClassInitialize(TestContext testContext) 
    { 
     host = new ServiceHost(typeof(MyService)); 
     host.AddServiceEndpoint(typeof(IMyContract), new NetTcpBinding(), address); 
     host.Open(); 
    } 

    [ClassCleanup()] 
    public static void MyClassCleanup() 
    { 
     if (host.State == CommunicationState.Opened) 
      host.Close(); 
    } 
    #endregion 

    [TestMethod] 
    public void UseUserNameCredentials() 
    { 
     using (MyContractClient proxy = 
      new MyContractClient(new NetTcpBinding(), address)) 
     { 
      proxy.ClientCredentials.UserName.UserName = "MyUsername"; 
      proxy.ClientCredentials.UserName.Password = "MyPassword"; 

      proxy.Open(); 
      Assert.AreEqual("EMS\\magood", proxy.GetUserName()); 
      proxy.Close(); 
     } 
    } 
}