UriTemplate WCF

2019-06-21 08:56发布

Is there a simple way to have multiple UriTemplates in the same definition.

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

For example I want /API/{id} and /API/{id}/ to call the same thing. I don't want it to matter if there is / at the end or not.

标签: c# wcf rest
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-21 08:57

This is only partially helpful, but the new WCF Web API library has a property on the HttpBehavior called TrailingSlashMode that can be set to Ignore or Redirect.

查看更多
戒情不戒烟
3楼-- · 2019-06-21 09:12

Not really simple, but you can use an operation selector in your behavior to strip the trailing '/', like in the example below.

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();
    }
}
查看更多
欢心
4楼-- · 2019-06-21 09:21

The easiest way I found to do this is to overload the function as explained here.

查看更多
登录 后发表回答