c#和.net中wcf头文件的类型转换问题

本文关键字:文件 类型转换 问题 wcf net | 更新日期: 2023-09-27 17:50:05

我现在正在使用visual studio 2013开发一个WCF服务。我的服务包含一个必须传递的自定义报头字段。字段名是"lisenseKey",是我开发的。WCF服务工作正常。现在我要调用我的服务进行测试。我在客户端项目中添加了一个服务引用。现在我像这样调用:

MyService.Myservice proxy = new MyService.Myservice();
proxy.LisenseKey = "xxxxxx";
Label1.Text = proxy.GetMessage(TextBox1.Text);

当我像这样分配许可键值时,它会显示红色下划线的错误:

"不能隐式地将类型字符串转换为MyService.MyService.string"

在这种情况下如何输入强制转换?或者有任何方法传递header?我不知道如何使用"MessageHeader"

c#和.net中wcf头文件的类型转换问题

这是我的服务代码。我只是想使用"GetMessage"方法。

[ServiceContract]
    public interface IMyservice
    {
        [OperationContract]
        void DoWork();
        [OperationContract]
        string GetMessage(string name);
    }
    public class MyServiceMessageInspector:System.ServiceModel.Dispatcher.IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request,System.ServiceModel.IClientChannel channel,
            System.ServiceModel.InstanceContext instanceContext)
        {
            if(request.Headers.FindHeader("LisenseKey","")==-1)
            {
                throw new FaultException("Lisense Key Was Not Provided");
            }
            var lisenseKey = request.Headers.GetHeader<string>("LisenseKey", "");
            if (string.IsNullOrEmpty(lisenseKey))
            {
                throw new FaultException("Lisnse key is not valid");
            }
            if(lisenseKey!="12345x")
            {
                throw new FaultException("Lisense key is not valid");
            }
            return instanceContext;
        }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply,object correlationState)
        {
        }
    }
    public class MyServiceMessageInspectorBehaviour:Attribute,System.ServiceModel.Description.IServiceBehavior
    {
        public void AddBindingParameters(System.ServiceModel.Description.ServiceDescription serviceDescription,
            System.ServiceModel.ServiceHostBase serviceHostBase,
            System.Collections.ObjectModel.Collection<System.ServiceModel.Description.ServiceEndpoint> endpoints,
            System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }
        public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription,
            System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach(ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
            {
                foreach(var endpointDispatcher in channelDispatcher.Endpoints)
                {
                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyServiceMessageInspector());
                }
            }
        }
        public void Validate(System.ServiceModel.Description.ServiceDescription serviceDescription,System.ServiceModel.ServiceHostBase serviceHostBase)
        {
        }
    }