2012-06-10 58 views
2

是否必須在每個操作上面編寫屬性[WebGet]才能通過「GET」訪問? 我希望我的默認訪問方法將是「GET」而不是「POST」。有沒有辦法在web.config/app.config上做到這一點?如何更改wcf中的默認http方法

+0

我想你需要指定你的方法提供什麼樣的操作,無論它是GET還是POST操作。我不認爲你不能在沒有指定屬性的情況下避開。 WebInvoke的默認值是POST,但對於GET,您需要使用WebGet屬性 – Rajesh

回答

1

只有在配置中沒有辦法做到這一點。您需要創建一個新的行爲,從WebHttpBehavior派生,並更改默認值(如果沒有任何內容,請添加[WebGet]) - 請參閱下面的代碼。然後,如果你願意,你可以定義一個行爲配置擴展來通過config來使用該行爲。

public class StackOverflow_10970052 
{ 
    [ServiceContract] 
    public class Service 
    { 
     [OperationContract] 
     public int Add(int x, int y) 
     { 
      return x + y; 
     } 
     [OperationContract] 
     public int Subtract(int x, int y) 
     { 
      return x + y; 
     } 
     [OperationContract, WebInvoke] 
     public string Echo(string input) 
     { 
      return input; 
     } 
    } 
    public class MyGetDefaultWebHttpBehavior : WebHttpBehavior 
    { 
     public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
     { 
      foreach (var operation in endpoint.Contract.Operations) 
      { 
       if (operation.Behaviors.Find<WebGetAttribute>() == null && operation.Behaviors.Find<WebInvokeAttribute>() == null) 
       { 
        operation.Behaviors.Add(new WebGetAttribute()); 
       } 
      } 

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

     WebClient c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=6&y=8")); 

     c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/Subtract?x=6&y=8")); 

     c = new WebClient(); 
     c.Headers[HttpRequestHeader.ContentType] = "application/json"; 
     Console.WriteLine(c.UploadString(baseAddress + "/Echo", "\"hello world\"")); 

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

我只是喜歡你解決問題的方式..... – ygaradon

相關問題