2013-12-19 79 views
0

{"The remote server returned an error: (405) Method Not Allowed}System.InvalidOperationException {System.Net.WebException}WCF POST方法

Web配置:

 <service name="Service" behaviorConfiguration="RestService">  
     <endpoint address="web" binding="webHttpBinding" 
        contract="IService" behaviorConfiguration="ServiceBehavior"> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="RestService"> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="false" /> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="ServiceBehavior"> 
      <webHttp /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <!--<protocolMapping> 
     <add binding="basicHttpsBinding" scheme="https"/> 
    </protocolMapping>--> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> 
    </system.serviceModel> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    <directoryBrowse enabled="true"/> 
    </system.webServer> 

服務:

public test TestPost(test testPost) 
    { 
     test objtest1 = new test(); 
     objtest1.Address = "Test"; 
     objtest1.Name = "Welcome"; 
     return objtest1; 
    } 


[DataContract] 
public class test 
{ 
    [DataMember(Order = 0)] 
    public string Name { get; set; } 
    [DataMember(Order = 1)] 
    public string Address { get; set; } 
} 


    [OperationContract] 
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "TestPost/")] 
    test TestPost(test i); 

使用招:

POST /RESTfulService/Service.svc/web/TestPost/ HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:50458 
Content-Length: 43 

HTTP/1.1 400 Bad Request 
Server: ASP.NET Development Server/11.0.0.0 
Date: Thu, 19 Dec 2013 07:19:44 GMT 
X-AspNet-Version: 4.0.30319 
Content-Length: 1647 
Cache-Control: private 
Content-Type: text/html 
Connection: Close 

GET方法工作正常,當我嘗試使用POST方法我得到錯誤

+0

顯示您正在發佈的實際XML請求......看起來問題出在請求中,因爲其他一切似乎都很好。 – Tisho

+0

我正在使用Json格式。格式爲 { 「Name」=「test」, 「Address」=「test」 } – user3118128

+0

Ops,我錯過了。好的,看看這個問題:http://stackoverflow.com/questions/575893/why-does-my-c-sharp-client-posting-to-my-wcf-rest-service-return-400-bad-req ,似乎是一樣的。 – Tisho

回答

0

我在本地上面的例子嘗試,發現你缺少一個HTTP標頭名爲

Content-Type: application/json 

還要確保你傳遞正確的JSON字符串在請求主體

{"Name" : "test", "Address" : "test"} 

上述技巧將幫助你擺脫了400個不好的要求。