2011-06-07 90 views
1

在運行時在佔位符中提供空字符串時,WebInvokeAttribute和UriTemplate解析程序如何運行?帶有空字符串的UriTemplate的WebInvoke

documentation似乎沒有涵蓋這一點。

在一些繼承的代碼中,我遇到了在空字符串傳遞時方法沒有被正確解析的情況。與其他Web方法沒有明顯的衝突。

謝謝!

更新:

在UriTemplate如:"/{x}/{y}?z={z}",什麼是,如果部分或全部值都設置爲「」空字符串的行爲,但是分隔符仍然存在,"/17/?z=""//apple?z=""//?z=%20""//?z="。另外,按照標準,瀏覽器允許在發送之前清理 URI嗎?

回答

-2

空字符串表示該操作的URI位於與端點相同的地址處 - 請參閱下面的示例以獲取更多信息。

public class StackOverflow_6267866 
{ 
    [ServiceContract] 
    public interface ITest1 
    { 
     [WebInvoke(UriTemplate = "")] 
     string EchoString(string text); 
    } 
    [ServiceContract] 
    public interface ITest2 
    { 
     [WebInvoke(UriTemplate = "", BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
     int Add(int x, int y); 
    } 
    public class Service : ITest1, ITest2 
    { 
     public string EchoString(string text) 
     { 
      return text; 
     } 

     public int Add(int x, int y) 
     { 
      return x + y; 
     } 
    } 
    static void SendPostRequest(string uri, string contentType, string body) 
    { 
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri); 
     req.Method = "POST"; 
     req.ContentType = contentType; 
     byte[] bodyBytes = Encoding.UTF8.GetBytes(body); 
     req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length); 
     req.GetRequestStream().Close(); 

     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); 
     foreach (string headerName in resp.Headers.AllKeys) 
     { 
      Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]); 
     } 
     Console.WriteLine(); 
     Stream respStream = resp.GetResponseStream(); 
     Console.WriteLine(new StreamReader(respStream).ReadToEnd()); 
     Console.WriteLine(); 
     Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* "); 
     Console.WriteLine(); 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.AddServiceEndpoint(typeof(ITest1), new WebHttpBinding(), "ITest1").Behaviors.Add(new WebHttpBehavior()); 
     host.AddServiceEndpoint(typeof(ITest2), new WebHttpBinding(), "ITest2").Behaviors.Add(new WebHttpBehavior()); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     SendPostRequest(baseAddress + "/ITest1", "application/json", "\"hello world\""); 
     SendPostRequest(baseAddress + "/ITest1/", "application/json", "\"hello world\""); 
     SendPostRequest(baseAddress + "/ITest2", "application/json", "{\"x\":123,\"y\":456}"); 
     SendPostRequest(baseAddress + "/ITest2/", "application/json", "{\"x\":123,\"y\":456}"); 

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

整個uri不爲空字符串,運行時爲空字符串值。 – 2011-06-07 16:54:24