是否可以在运行时更改UriTemplate

1 wcf webinvoke uritemplate

我有以下WebInvoke属性:

        [OperationContract]
        [WebInvoke(
        Method         = "POST",
        UriTemplate    = "",
        BodyStyle      = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat  = WebMessageFormat.Json)]
Run Code Online (Sandbox Code Playgroud)

我希望根据运行时值设置UriTemplate值.有没有办法在运行时在服务实现中设置UriTemplate?

car*_*ira 5

是的,你可以做到这一点,如果你使用的是添加了终结点行为之前WebHttpBehavior.此行为可以更改WebGetAttribute/ 的属性WebInvokeAttribute.下面的代码显示了一个更改UriTemplatea属性的行为示例[WebGet],但它也可以正常工作[WebInvoke].

public class StackOverflow_7590279
{
    [ServiceContract]
    public class Service
    {
        [WebGet(UriTemplate = "/Add?x={x}&y={y}", ResponseFormat = WebMessageFormat.Json)]
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
    public class MyBehavior : IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            foreach (OperationDescription od in endpoint.Contract.Operations)
            {
                if (od.Name == "Add")
                {
                    WebGetAttribute wga = od.Behaviors.Find<WebGetAttribute>();
                    if (wga != null)
                    {
                        wga.UriTemplate = "/Add?first={x}&second={y}";
                    }
                }
            }
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        var endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "");

        // This has to go BEFORE WebHttpBehavior
        endpoint.Behaviors.Add(new MyBehavior());

        endpoint.Behaviors.Add(new WebHttpBehavior());

        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine("Using the original template (values won't be received)");
        Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=45&y=67"));

        c = new WebClient();
        Console.WriteLine("Using the modified template (will work out fine)");
        Console.WriteLine(c.DownloadString(baseAddress + "/Add?first=45&second=67"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)