获取WCF请求的域名?

时间:2009-06-01 17:37:15

标签: wcf .net-3.5

如何获取请求者的域名或完整URL?

1 个答案:

答案 0 :(得分:3)

我不确定我理解你的问题,但是如果你需要Windows用户的域名来调用服务操作,请使用:

OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name

这将返回“{domain} \ {username}”。

试试这个让我知道你的想法(你可能想把这段代码粘贴到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();
        }
    }
}