UriTemplate WCF

时间:2011-05-20 14:44:01

标签: c# wcf rest

是否有一种简单的方法可以在同一个定义中使用多个UriTemplates。

 [WebGet(UriTemplate = "{id}")]

例如,我想要/ API / {id}和/ API / {id} /来调用相同的东西。如果有/不在最后,我不想要它。

3 个答案:

答案 0 :(得分:3)

不是很简单,但您可以在行为中使用操作选择器去除尾随的'/',如下例所示。

public class StackOverflow_6073581_751090
{
    [ServiceContract]
    public interface ITest
    {
        [WebGet(UriTemplate = "/API/{id}")]
        string Get(string id);
    }
    public class Service : ITest
    {
        public string Get(string id)
        {
            return id;
        }
    }
    public class MyBehavior : WebHttpBehavior
    {
        protected override WebHttpDispatchOperationSelector GetOperationSelector(ServiceEndpoint endpoint)
        {
            return new MySelector(endpoint);
        }

        class MySelector : WebHttpDispatchOperationSelector
        {
            public MySelector(ServiceEndpoint endpoint) : base(endpoint) { }

            protected override string SelectOperation(ref Message message, out bool uriMatched)
            {
                string result = base.SelectOperation(ref message, out uriMatched);
                if (!uriMatched)
                {
                    string address = message.Headers.To.AbsoluteUri;
                    if (address.EndsWith("/"))
                    {
                        message.Headers.To = new Uri(address.Substring(0, address.Length - 1));
                    }

                    result = base.SelectOperation(ref message, out uriMatched);
                }

                return result;
            }
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "").Behaviors.Add(new MyBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/API/2"));
        Console.WriteLine(c.DownloadString(baseAddress + "/API/2/"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

答案 1 :(得分:1)

这只是部分有用,但新的WCF Web API库在HttpBehavior上有一个名为TrailingSlashMode的属性,可以设置为Ignore或Redirect。

答案 2 :(得分:1)

我发现这样做的最简单方法是重载函数as explained here