Restful WCF return http 400 - c#

I have a web service interface looks like
[ServiceContract]
public interface IASchoolsWebService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "Categories?shortString={shortString}")]
IEnumerable<string> GetCategoriesByShortString(string shortString);
}
and the implementation looks like
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
public class ASchoolsWebService: IASchoolsWebService
{
public IEnumerable<string> GetCategoriesByShortString(string shortString)
{
// my Implementation here
}
}
the web service works fine using web reference , but I want to use as RESTFULL service for further mobuke applicaitons any idea why I get 4oo if I called using browser
mywebservice.svc/Categories
I use web.conig like :
<behaviors>
<serviceBehaviors>
<behavior name="SchoolsWebServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
<behavior name="SchoolsWebServiceSecureBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="ArabicEWorld.WebService.ArabicEWorldWebService" behaviorConfiguration="SchoolsWebServiceBehavior">
<endpoint name="UnsecureEndpoint" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfig" contract="ArabicEWorld.WebService.IArabicEWorldWebService" />
<!--<endpoint name="SecureEndpoint"
binding="basicHttpBinding"
bindingConfiguration="secureBasicHttpBindingConfig"
contract="MedStreaming.Schools.Server.WebService.IMedStreamingSchoolsWebService"/>-->
</service>
</services>

Http error code 400 signifies "BadData" and commonly means you didnt send the proper parameters. In your code, you are expecting to receive a query parameter called shortString:
"Catagories?shortString={shortString}"
But you do not provide that parameter in your browser attempt:
mywebservice.svc/Catagories
If you were to instead use:
mywebservice.svc/Catagories?shortString=testString
you would be sending the proper parameter.

Your code is working perfectly with URL="http://localhost:54632/mywebservice.svc/Categories?shortString=shortString"
But if you are returning other type rather than 'IEnumerable < String >' then You need to use [ServiceKnownType] in interface.. depending on what you are return from your method...
Thanks,

Related

Using REST GET in WCF as 2nd endpoint

I trying to add 2nd endpoint in existing WCF Application and my REST method doesn't work.
I created new Interface
[ServiceContract]
public interface IRestService
{
[OperationContract]
[WebGet(UriTemplate = "RestURI", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string SomeMethod();
}
And implemented it in existing service
public string SomeMethodImplementation()
{
//some logic
}
I'm trying to access this method using basicaddress/service/RestURI but getting 400 Bad Request response.
After that I added protocolMapping, 2nd endpoint and endpoint behavior to config file but it didn't help.
Right now my config file looks like this:
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding"/>
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="servicename">
<endpoint address="" binding="webHttpBinding" contract="IRestService" behaviorConfiguration="web"/>
<endpoint address="" binding="basicHttpBinding" contract="ISoapService"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" receiveTimeout="00:10:00" sendTimeout="00:10:00">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
</binding>
</basicHttpBinding>
</bindings>
I'm not getting any 400 anymore but instead of that 'cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher.' error appeared. Also after adding protocolMapping, my soap methods have disappeared when I open wsdl in browser. Without it my rest method can be seen in the list like this:
<wsdl:port name="BasicHttpBinding_IRestService" binding="i0:BasicHttpBinding_IRestService">
After that I added AddressFilterMode = AddressFilterMode.Any) in attributes of my Service but it doesn't help.
I found a lot of answers here but somehow not a single one help me to resolve this problem.
What did I miss?
I found the solution after I installed WCF for visual studio. All this time I had wrong namespaces in my web.config and had no idea but VS marked it after installing module. I added right namespace and problem went away. I really suggest to install WCF in VS.
The issue boils down to the fact that we fail to host the service in Restful style.
Ordinarily, there are two ways to configure the Restful style service created by Webhttpbinding.
1.Using the service section to configure the interface and implementation.
<services>
<service name="WcfService3.Service1">
<endpoint address="" binding="webHttpBinding" contract="WcfService3.IService1" behaviorConfiguration="rest"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
There are two points we should pay attention to. In the service section, we are supposed to use the corresponding interface and implementation.
<service name="WcfService3.Service1">
<endpoint address="" binding="webHttpBinding" contract="WcfService3.IService1"
Adding a webhttp endpoint behavior also is essential then apply it by using Behaviorconfiguration property.
behaviorConfiguration="mybinding"
In the latest feature, we could create a WCF Restful style service with protocol mapping.
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
It should be noted that we need to add an endpoint behavior without a name.
Based on your configuration, since you have multiple interfaces I suggest you remove the service section and host the service with a protocol mapping feature.
1. Remove service section in the configuration.
2. Remove the name of the endpoint behavior.
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding"/>
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
Then we could access the service by the below Uri.
basicaddress/service.svc/RestURI
Feel free to let me know if there is anything I can help with.

WCF REST service not responding and issuing 500 error

I tried creating a WCF REST service in our existing ASP.NET application. However, when I try to browse to my service using the web browser, it says "This site can't be reached".
The URL I'm trying to hit is: http://localhost:81/ExternalServices/WS/Snap/REST/SnapService.svc
Also, when I try hitting it using a client tool, it gives me error 500.
// SnapService.svc
<% #ServiceHost Service = "DomainName.ProjectName.WebApp.ExternalServices.WS.Snap.REST.SnapService" Language="C#" %>
// ISnapService.cs
namespace DomainName.ProjectName.WebApp.ExternalServices.WS.Snap.REST
{
[ServiceContract]
public interface ISnapService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UpdateLender")]
string UpdateLender(string userName, string password, string portfolioCode, string xmlRequest);
}
}
// SnapService.cs
namespace DomainName.ProjectName.WebApp.ExternalServices.WS.Snap.REST
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SnapService : ISnapService
{
public string UpdateLender(string userName, string password, string portfolioCode, string xmlRequest)
{
// implementation here
return SnapServiceHelper.UpdateLender(userName, password, portfolioCode, xmlRequest);
}
}
}
// Web.config
<system.serviceModel>
<services>
<service name="DomainName.ProjectName.WebApp.ExternalServices.WS.Snap.REST.SnapService" behaviorConfiguration="defaultBehaviour">
<endpoint name="webHttpsBinding" address="" binding="webHttpBinding" contract="DomainName.ProjectName.WebApp.ExternalServices.WS.Snap.REST.ISnapService" behaviorConfiguration="webHttp" bindingConfiguration="webHttpTransportSecurity"/>
<endpoint name="mexHttpsBinding" address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity">
<security mode="Transport"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="defaultBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
EDIT: Enabled debugging to write to a log file. Here's the exception I get when I attempt to browse to the link above:
Operation 'UpdateLender' of contract 'ISnapService' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.

Defining baseURL and EndPoint

I made a WCF with three methods:
[ServiceContract]
public interface IService1
{
[OperationContract]
String devolverPisosA();
[OperationContract]
String devolverPisosV();
[OperationContract]
String devolverNoticias();
}
I need to define baseAddress and EndPoint in Web.config file but I don´t know how:
I´m trying this (and some variations) but this is not working... (between system.serviceModel)
<services>
<service
name="ProyectoJosephWCF.Service1">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/Iservice1/"/>
</baseAddresses>
</host>
<endpoint address="devolverPisoA"
binding="wsHttpBinding"
contract="ProyectoJosephWCF.Service1" />
<endpoint address="devolverPisoV"
binding="wsHttpBinding"
contract="ProyectoJosephWCF.Service1" />
<endpoint address="devolverNoticias"
binding="wsHttpBinding"
contract="ProyectoJosephWCF.Service1" />
</service>
</services>
EDITED: If I´m not defining the baseAddress and endpoint before (using default configuration which was created when I created the project), and I launched the Services1.svc, I can reach the result json through testing windows but I can´t (or at least I don´t know how) to reach that JSON result from Android (by Retrofit). I supposed that I configured Retrofit (baseAddress and Endpoint values wrong), so I decided to set those values by my own...
For that I set the code before in Web.config, but I can´t reach them as well...
Beside, I would like to reach JSON result by Mozilla (in browser I mean), because someone said me that could me help to understand what baseAddress and Endpoint I´m using...
EDITED2: Behaviors are settings as:
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
And still don´t reach result by android or browser...
You need to set httpGetEnabled="true" for having WSDL available like below
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
Include the same behavior configuration in your service declaration like
<service name="ProyectoJosephWCF.Service1"
behaviorConfiguration="NewBehavior">
See serviceMetadata for more information.
Finally... Check it out if you need it.
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
And:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "devolverPisoA")]
List<pisosAlquiler> devolverPisosA();

My page doesnt seem to let me do ajax calls to my service files methods

I get a error 400, Bad Request.
I have a set of pages that i was trying to write. (Listing only relevant)
./Webpage.aspx
./webservices/WebCalls.svc
./webservices/IWebCalls.cs
./Web.config
and i was looking all over to allow my frontend to communicate with the Webcalls page like follows:
$.ajax({
url: "webservices/WebCalls.svc/DoWork",
success: function(){
console.log(arguments);
}
});
but it doesnt seem to work.
I was thinking to create the files as such:
WebCalls.svc:
public class WebCalls: IWebCalls
{
public string DoWork()
{
return "{\"hello\":\"Chop Wood, Carry Water.\"}";
}
}
and IWebCalls.cs:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public interface IWebCalls
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "DoWork")]
string DoWork();
}
and in my webConfig, i thought i set it up correctly:
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" httpGetUrl=""/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<services>
<service behaviorConfiguration="ServiceBehavior" name="MyProj.WebCalls">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
bindingConfiguration="LargeWeb" name="LargeWeb" contract="MyProj.webservices.IWebCalls" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="LargeWeb"
maxBufferPoolSize="15000000"
maxReceivedMessageSize="15000000"
maxBufferSize="15000000">
<readerQuotas
maxArrayLength="15000000"
maxBytesPerRead="15000000"
maxDepth="32"
maxNameTableCharCount="15000000"
maxStringContentLength="15000000"
/>
</binding>
</webHttpBinding>
</bindings>
When i run it, it just tells me that it has created a service, but when i try to call: DoWork it gets a 400 error.
Am I doing something wrong with my approach? Im just trying to build up a set of pages such that i can query for data. Originally, i was going to create a GenericHander.asxh for EACH function i wanted to create, but i thought that was too much space. I knew something like this was an option, but it seems that it doesnt work.
You may have decorated the wrong interface ITestService. Instead check the declaration of IWebCalls.
EDIT: Hmm.. I see you updated question ...
I think your services name should probably be name="MyProj.webservices.WebCalls" - but assuming that too is a typo, the only issue I see is that mex endpoint should not be there. mex endpoints are not meant for REST based services.

Error: Cannot obtain Metadata from WCF service

I have a successfully running WCF service that I can call using javascript. However I want to invoke it using the WCF test client and im having difficulty doing this. I am told that I need to make sure I have enabled meta data publishing at the specified address. After reading the documentation I just cant see what im meant to do this is my configuration:
<system.serviceModel>
<services>
<service name="CommentSessionIDWCFService"
behaviorConfiguration="CommentSessionIDBehavior">
<endpoint
address=""
behaviorConfiguration="CountryProvinceBehavior"
binding="webHttpBinding"
contract="ICommentSessionIDWCFService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CommentSessionIDBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="CountryProvinceBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
I've read other posts but I can't see what to populate and I just keep getting errors. Q's..
Am I right in saying that I need to configure a complete new service in my config to show the metadata?
What do I add to the configuration to make this meta data published so I can invoke with the client?
You need a metadata endpoint for your service, here`s an example.
<services>
<service name="MyService" behaviorConfiguration="MEX">
<endpoint
address="http://localhost:8000/MEX"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MEX">
<serviceMetadata/>
</behavior>
</serviceBehaviors>
</behaviors>
I had a similar problem after changing the config file in the TestClient with right click and "edit with svceditor" to increase my maxbuffersize. If someone did that mistake as well, try rebuilding your project.
Add
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
Set httpGetEnabled to true and set the includeExceptionDetailInFaults to false:
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>

Categories