WCF rest service for list - json not working - json

My wcf reset service has only 2 contracts, one is working always and the other did not work.
Service Code:
Public Class BasicServ
Implements IBasicServ
Public Function DoWork() Implements IBasicServ.DoWork
Return "Working"
End Function
Function Authorize(ByVal id As String, ByVal pw As String) Implements IBasicServ.Authorize
Dim c As New List(Of Guid)
For i = 0 To 10
c.Add(Guid.NewGuid)
Next
Return c
'Return Guid.NewGuid
End Function
End Class
Contract File code:
<ServiceContract()>
Public Interface IBasicServ
<OperationContract()>
<WebGet(UriTemplate:="test/", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function DoWork()
<OperationContract()>
<WebGet(UriTemplate:="Authorize/{id}/{pw}", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function Authorize(ByVal id As String, ByVal pw As String)
End Interface
Web Config File:
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="messagelistener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="d:\logs\myMessages.svclog"></add>
</listeners>
</source>
</sources>
<trace autoflush="true"/>
</system.diagnostics>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true"
logMessagesAtServiceLevel="false"
logMessagesAtTransportLevel="false"
logMalformedMessages="true"
maxMessagesToLog="5000"
maxSizeOfMessageToLog="2000">
</messageLogging>
</diagnostics>
<services>
<service behaviorConfiguration="ServBehav" name="AssistantWcf.BasicServ">
<endpoint address="auth" behaviorConfiguration="EndBehav" binding="webHttpBinding" name="endpointname" contract="AssistantWcf.IBasicServ" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="EndBehav">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServBehav">
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />
<!-- 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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
While debugging/testing, I found that, if I return only 1 GUID in Authoriza method, it is working, but when I am sending a list of GUID, it is not working, and the SVClog file is not getting created. Could you please help me understand WCF REST service better. Thank you.

From above comments and few experiments, the solution for the question is that a return type is not compulsory if it is string, but if anything else, return type must be specified. Better if return type is provided always.

Related

WCF service Post error on IIS 6

I have developed a REST service that used to run localy on my PC and had no issues!!I have hosted my wcf on a windows server 2008-r2 IIS 7.5, in order to call my service from an IP. I am using the get method with a JSON and all works fine, but when i try the post( with chrome plugin) i get 405 error and 500 error. I checked the MIME-TYPES and added json for IIS. Any solution or suggestiong how to resolve this error would be very useful.
I will post my webconfig and ISERVICE files as well.
My webConfig file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="Services.webHttpBehavior">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- 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>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
<behavior name="Services.webHttpBehavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!-- <staticContent>
<mimeMap fileExtension=".json" mimeType="application/json"/>
</staticContent>-->
</system.webServer>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\wcflog3.txt" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
My Service Implementtion is as followes:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "xml/{str}")]
string XMLData(string str);
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "jsoncheckifexists")]
bool CheckIfExists(RestService.RestServiceImpl.UrlObject data);
The GET is working just fine, I try the POST calling the function CheckIfExists:
public bool CheckIfExists(UrlObject urlObject)
{
string link= urlObject.url;
//Standard logon to CRM procedure(Framework)
if abc=true
return true;
else false;
}

how to invoke wcf service having list parameter

I have a webservice as below
<OperationContract()>
<Web.WebGet(UriTemplate:="/GetData?strErrMsg={strErrMsg}&chrErrFlg={chrErrFlg}", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)> _
Function GetData(ByRef strErrMsg As System.Collections.Generic.List(Of String), ByRef chrErrFlg As String) As String
And I am trying to fetch it as
http://BedTypeMasterService.svc/GetData?strErrMsg="ff"&chrErrFlg="dd"
But it is giving following error
Operation 'GetData' in contract 'iBedTypeMaster' has a query variable named 'strErrMsg' of type 'System.Collections.Generic.List1[System.String]', but type 'System.Collections.Generic.List1[System.String]' is not convertible by 'QueryStringConverter'. Variables for UriTemplate query values must have types that can be converted by 'QueryStringConverter'.
Please help me out to solve this
As per provided link i try like this
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<customWebHttp/>
</behavior>
</endpointBehaviors>
<extensions>
<behaviorExtensions>
<add name="customWebHttp" type="WcfServices.BedTypeMaster.bclsBedTypeMaster, WcfServices" />
</behaviorExtensions>
</extensions>
<service behaviorConfiguration="ServiceBehavior" name="WcfServices.BedTypeMaster.bclsBedTypeMaster">
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP" contract="WcfServices.BedTypeMaster.iBedTypeMaster"
behaviorConfiguration="webHttpBehavior">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="basicHttpBinding" contract="IMetadataExchange" />
</service>

WCF Problems Integrating with JSON

I am having problems calling my WCF service via jquery / JSON.
So far I have done the following:
In VS 2010, start a new "WCF Service Application" project. Visual Studio then auto generates a sample service called IService / Service, which has the function
string GetData(int value);
Inside IService.cs I add the WebGet attribute, as follows:
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
Inside my web.config I have
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfService1.Service1"
behaviorConfiguration="ServiceBehavior">
<endpoint contract="WcfService1.IService1"
binding="webHttpBinding"
behaviorConfiguration="AjaxBehavior" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I build and run the service, and on opening
http://localhost:58403/Service1.svc/GetData?value=1
in my web browser it prints out (as expected)
{"d":"You entered: 1"}
5, I create a new asp.net web application project. Inside default.aspx, I add
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var request = $.ajax({
type: "GET",
url: "http://localhost:58403/Service1.svc/GetData",
data: { value: "1" }
});
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
</script>
6, I build and run that, but instead of hitting the done callback, it hits the error callback and alerts "Request failed: error"
If I set a breakpoint in the service code, I can see that the GetData function is being hit and appears to return successfully. I can also see in the firebug net console that the web service call is returning a status code of "200 OK", but the error handler callback is being hit instead of the success callback. Does anyone know what I am doing wrong?
Well, I managed to solve this on my own. In case anyone is reading this and is curious, I changed the WCF service and web application so that they now both run via IIS instead of Visual Studio's web server.
So I now have
http://localhost/WcfService1/Service1.svc/GetData?value=1
http://localhost/WebApplication1/
I believe it was not working previously due to cross domain requests. Even though it was same domain, just different port numbers, I believe this still counts as cross domain?

WCF Json GET Service: Check that the sender and receiver's EndpointAddresses agree

I've been working in .NET for a while now, but I'm new to WCF. I'm trying to create my very first WCF service using JSON. I thought I would start really, really simple and then build from there. But I have somehow managed to screw up even the most simple of services. Here's what I've got so far.
Web.Config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="MarathonInfo.MarathonInfoService">
<endpoint address="http://localhost:10298/MarathonInfoService.svc" binding="webHttpBinding" contract="MarathonInfo.IMarathonInfo" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Then, in the service file:
namespace MarathonInfo
{
public class MarathonInfoService : IMarathonInfo
{
public String GetData()
{
return "Hello World";
}
}
}
And in the interface:
namespace MarathonInfo
{
[ServiceContract]
public interface IMarathonInfo
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
String GetData();
}
}
So, when I go to this url:
http://localhost:10298/MarathonInfoService.svc/GetData
I get this error:
The message with To
'http://localhost:10298/MarathonInfoService.svc/GetData' cannot be
processed at the receiver, due to an AddressFilter mismatch at the
EndpointDispatcher. Check that the sender and receiver's
EndpointAddresses agree.
I am able to execute the service just fine through Visual Studio in debug mode. But in the browser, I only get that error.
What am I doing wrong?
Thanks!
Casey
If you want to create a WCF WebHTTP Endpoint (i.e., one which returns JSON, and uses the [WebGet] / [WebInvoke] attributes), the endpoint needs to have the <webHttp/> behavior associated with it.
<system.serviceModel>
<services>
<service name="MarathonInfo.MarathonInfoService">
<endpoint address="http://localhost:10298/MarathonInfoService.svc"
binding="webHttpBinding"
contract="MarathonInfo.IMarathonInfo"
behaviorConfiguration="Web"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="Web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
</system.serviceModel>

WCF and JSON binding

I am trying to create a wcf service that returns json. I have some problems with my config file and i also don't know how to test it.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="ContactLibraryJSON.ContactLibrary">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="JSONEndpointBehavior"
contract="ContactLibraryJSON.IContactServiceJSON" />
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://192.168.1.31/ContactLibraryJSON" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="JSONEndpointBehavior">
<webHttp/>
</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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I still get
"Cannot add the behavior extension webhttp to the service behavior
names JSONEndpointBehavior because the underlying behavior type does
not implement the IServiceBehaviorInterface"
Contact is defined like :
[DataContract(Name="Contact")]
public class Contact
{
[DataMember(Name="FirstName")]
public string firstName=null;
[DataMember(Name="LastName")]
public string lastName=null;
[DataMember(Name="Email")]
public string email=null;
[DataMember(Name = "Age")]
public int age = 0;
[DataMember(Name = "Street")]
public string street=null;
[DataMember(Name = "City")]
public string city=null;
[DataMember(Name = "Country")]
public string country=null;
}
IContactService is defined like :
[ServiceContract]
public interface IContactServiceJSON
{
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "")]
Contact GetContact();
}
The implementation of GetContact:
public Contact GetContact()
{
return new Contact()
{
firstName = "primulNume",
lastName = "alDoileaNume",
age = 33,
city = "Cluj",
country = "Romania",
email = "ceva#mail.com",
street = "Bizusa 8"
};
}
My service runs on another computer in my lan. Base address is like: http://192.168.1.xxx/ContactLibraryService. ContactLibraryService is hosted by IIS and is converted to an application.
You need to add the <webHttp/> to the list of endpoint behaviors. Also, the endpoint needs to use the webHttpBinding. And finally, to respond to GET HTTP requests, you need to use the WebGet attribute (instead of WebInvoke(Method="GET").
<system.serviceModel>
<services>
<service name="ContactLibrary.ContactLibrary">
<endpoint address=""
binding="webHttpBinding"
behaviorConfiguration="JSONEndpointBehavior"
contract="ContactLibrary.IContact"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint address="ws"
binding="wsHttpBinding"
bindingConfiguration=""
contract="ContactLibrary.IContact" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/ContactLibrary" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="JSONEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
And the service contract:
[ServiceContract]
public interface IContact
{
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "contact")]
Contact GetContact(int idContact);
}
It's not good that you have Service Contract IContact and Data Contact Contact. Rename Service Contract like IContactService.
<services>
<service name="ContactLibrary.ContactService">
<endpoint address="" binding="webHttpBinding" contract="ContactLibrary.IContactService" behaviorConfiguration="JsonBehavior" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
During Debug time (it looks you have WCF library), service address will be http://localhost:8732/contact
I think you missed bindings here you have to add webHttpBinding and basichttpbing under the bindings tab in system.serviceModel tag.
<services>
<service name="VInfotech.Server.Intranet.IntranetService" behaviorConfiguration="IntranetService.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" contract="VInfotech.Server.Intranet.IIntranet">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
<service name="VInfotech.Server.Intranet.MobileServicesController" behaviorConfiguration="ServBehave">
<endpoint address="RestService" bindingConfiguration="StreamedRequestWebBinding" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="VInfotech.Server.Intranet.IMobileServices" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="StreamedRequestWebBinding"
bypassProxyOnLocal="true"
useDefaultWebProxy="false"
hostNameComparisonMode="WeakWildcard"
sendTimeout="10:15:00"
openTimeout="10:15:00"
receiveTimeout="10:15:00"
maxReceivedMessageSize="9223372036854775807"
maxBufferPoolSize="9223372036854775807"
maxBufferSize="2147483647"
transferMode="StreamedRequest" >
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="Binding1" closeTimeout="04:01:00" openTimeout="04:01:00" receiveTimeout="04:10:00" sendTimeout="04:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="1073741824" maxBufferPoolSize="1073741824" maxReceivedMessageSize="1073741824" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="1073741824" maxStringContentLength="1073741824" maxArrayLength="1073741824" maxBytesPerRead="1073741824" maxNameTableCharCount="1073741824"/>
</binding>
<!-- For Cyber Source bindings-->
<binding name="ITransactionProcessor" closeTimeout="04:01:00" openTimeout="04:01:00" receiveTimeout="04:10:00" sendTimeout="04:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="1073741824" maxBufferPoolSize="1073741824" maxReceivedMessageSize="1073741824" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="1073741824" maxStringContentLength="1073741824" maxArrayLength="1073741824" maxBytesPerRead="1073741824" maxNameTableCharCount="1073741824"/>
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
<!--Cyber Source bindings ends here-->
</bindings>