C# UriTemplate WCF
是否有一种简单的方法可以在同一定义中包含多个UriTemplatesC# UriTemplate WCF,c#,wcf,rest,C#,Wcf,Rest,是否有一种简单的方法可以在同一定义中包含多个UriTemplates [WebGet(UriTemplate = "{id}")] 例如,我希望/API/{id}和/API/{id}/调用相同的东西。我不想让结尾是否有/有关系。不是很简单,但您可以在行为中使用操作选择器来去除尾随的“/”,如下面的示例所示 public class StackOverflow_6073581_751090 { [ServiceContract] public interface ITest
[WebGet(UriTemplate = "{id}")]
例如,我希望/API/{id}和/API/{id}/调用相同的东西。我不想让结尾是否有/有关系。不是很简单,但您可以在行为中使用操作选择器来去除尾随的“/”,如下面的示例所示
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();
}
}
这只是部分有用,但新库在HttpBehavior上有一个名为TrailingSlashMode的属性,可以设置为忽略或重定向 我发现最简单的方法是重载函数。你的意思是
/API/{id}和/API{id}/
还是/API/{id}和/API/{id}/
?是的……会更正的……谢谢!是否有这样的操作:[WebGet(UriTemplate=“{id},{id}/”)或[WebGet(UriTemplate=“{id}}|{id}/”]否,每个操作描述都与一个UriTemplate相关联。你可以有多个操作(每个都有自己的模板),在其中一个操作中,你只需调用另一个。是的-我只是希望以某种方式避免这种情况…hmmis有一些方法可以在UriTemplate类中设置IgnoreTrailingSlash属性,我不这么认为,因为选择器没有公开一种方法来更改它创建的UriTemplate。