简体   繁体   中英

WCF REST service returns (400) Bad Request

I am new to WCF REST, I created a simple WCF application and try to consume it, but I keep getting an error:

The remote server returned an error: (400) Bad Request

My method :

[OperationContract]
[WebGet(UriTemplate="mymethod")]
string nameInput();

Consumed by using this code:

string uri = "http://localhost:53551/HelloNameService.svc/mymethod";
req = (HttpWebRequest)WebRequest.Create(uri);

try
{
    resp = req.GetResponse() as HttpWebResponse;
}
catch(Exception ex)
{
    Console.WriteLine(ex);
}

Stream stream = resp.GetResponseStream();
StreamReader reader = new StreamReader(stream);

string value = reader.ReadToEnd();
label1.Text = value;

web.config:

<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="mexBehaviors">
                    <serviceMetadata httpGetEnabled="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service name="MyServiceBecouseError.MyNameService" 
                     behaviorConfiguration="mexBehaviors">
                <endpoint 
                    address="" 
                    binding="basicHttpBinding" 
                    contract="MyServiceBecouseError.IMyNameService"/>
            </service>
        </services>
    </system.serviceModel>
    <system.webServer>
        <directoryBrowse enabled="true"/>
    </system.webServer>
    <system.web>
        <compilation debug="true"/>
    </system.web>
</configuration>

You are missing endpoint with webHttpBinding. Please use following configuration and you should be good.

  <configuration>
    <system.serviceModel>
      <services>
        <service behaviorConfiguration="MyServiceBehavior" name="MyService">
          <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" contract="MyServiceBecouseError.IMyNameService"/>                 
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
   </system.serviceModel>
  </configuration>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM