WCF rest service: unable to call methods - wcf

Please tell me I'm doing something stupid in setting up my wcf rest service.
I've create a web application and added a wcf service to it.
Here is my web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WebApplication1.Service1">
<endpoint address="../Service1" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WebApplication1.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
And my service interface:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "data/{value}", ResponseFormat = WebMessageFormat.Json)]
Person GetData(string value);
}
And my service code:
public class Service1 : IService1
{
public Person GetData(string value)
{
return new Person()
{
Id = Convert.ToInt32(value),
Name = "John Doe"
};
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
I have no problems browsing to the service
http://localhost/RoleProviderSite/Service1.svc
but as soon as I add the data/10
http://localhost/RoleProviderSite/Service1.svc/data/10
"There was no channel actively listening at 'http://mymachinename/RoleProviderSite/Service1.svc/data/10"
I would have thought that adding the "[WebGet(UriTemplate = "data/{value}", ResponseFormat = WebMessageFormat.Json)]" would mean that this url would be accessible, but maybe I'm missing something?
I'm using :
Internet Information Services, Version: 5.1
and XP OS
Thanks very much for any help.

remove the address in the endpoint and your URI should work as expected. You cannot use relative addressing like that for your endpoint

Related

WCF service host cannot find any service metadata. Please Check if metadata is enabled

My App.config file is
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="WcfJsonRestService.Service1">
<endpoint address="http://localhost:8733/service1"
binding="webHttpBinding"
contract="WcfJsonRestService.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
My service1.cs code is as below
using System;
using System.ServiceModel.Web;
namespace WcfJsonRestService
{
public class Service1 : IService1
{
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}")]
public Person GetData(string id)
{
// lookup person with the requested id
return new Person()
{
Id = Convert.ToInt32(id),
Name = "Leo Messi"
};
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Initially this was giving issue as
WCF Service Host Configuration - Please try changing the HTTP port to 8733
So I had followed Executing the following code in CMD
netsh http add urlacl url=http://+:8733/ user=WORK\Clara
After executing this code I am facing new error as below
How can I resolve this issue?
I have also tried updating the App.Config as said over below link but then after I was getting some another error
WCF service host cannot find any service metadata
You are missing service metadata behavior configuration. Please add below configuration:
<configuration>
<system.serviceModel>
<services>
<service name="WcfJsonRestService.Service1">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733"/>
</baseAddresses>
</host>
<endpoint address="service1"
binding="webHttpBinding"
contract="WcfJsonRestService.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled ="true"/>
</behavior>
</serviceBehaviors>
</behaviors>

WCF JSON Format - while consuming in Client side getting an error message

Client side Code
I have created web application and added service reference to the Client Project
I tried creating a client Object like this:
Service1Client a = new Service1Client();
but getting an error message :
Could not find default endpoint element that references contract 'ServiceReference_test.IService1' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this contract could be found in the client element.
Could you please let me know what mistake am I doing, I am new to WCF please help me
WCF service which returns JSON Format:
namespace WcfService1
{
public class Service1 : IService1
{
public string GetData(string Id)
{
return ("You entered: " + Id);
}
}
}
namespace WcfService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetData/{Id}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped
)]
string GetData(string Id);
// TODO: Add your service operations here
}
}
Web.Config file
<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WcfService1.IService1"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>-->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
You should add following tags in your client App.config or Web.config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding" />
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/fine_service/FineService/soap"
binding="webHttpBinding" bindingConfiguration="WebHttpBinding"
contract="ServiceReference1.IService1" name="WebHttpBinding" />
</client>
</system.serviceModel>
if you have this tags in your cofig file then make sure that client endpoint contract name should be the same as it is in your service endpoint. In your case contract name is IService1
EDIT:
also see this

How to host my WCF Service on IIS

I want to host my service on IIS and let people from local network use it. Here is my interface:
namespace SubscriptionService
{
[ServiceContract]
public interface ISubsService
{
// SOA
[OperationContract]
[WebGet(UriTemplate = "registerevent/{serviceId}/{name}/{description}")]
string RegisterEvent(string serviceId, string name, string description);
[OperationContract]
[WebGet(UriTemplate = "unregisterevent/{serviceId}/{name}")]
string UnregisterEvent(string serviceId, string name);
[OperationContract]
[WebGet(UriTemplate = "riseevent/{serviceId}/{name}")]
string RiseEvent(string serviceId, string name);
// REST
[OperationContract]
[WebGet(UriTemplate = "events/{token}", ResponseFormat = WebMessageFormat.Json)]
List<EventInfo> EventsList(string token);
[OperationContract]
[WebGet(UriTemplate = "subscribe/{token}/{serviceId}/{name}")]
string Subscribe(string token, string serviceId, string name);
[OperationContract]
[WebGet(UriTemplate = "unsubscribe/{token}/{serviceId}/{name}")]
string UnSubscribe(string token, string serviceId, string name);
}
}
And web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="SubscriptionService.SubsService">
<endpoint address="soap" binding="basicHttpBinding" contract="SubscriptionService.ISubsService"></endpoint>
<endpoint address="rest" binding="webHttpBinding" contract="SubscriptionService.ISubsService" behaviorConfiguration="web"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<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>
</configuration>
I need to use both soa and rest methods. Is there something wrong with my config? I tried to add this service on IIS, but it didn't work. I set sitename "my service", path to directory with svc file, host name "myservice" and port. And it didn't work. A was not able to access it even on my local machine.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.?

trying to build a RestFull service with wcf running in the WcfTestClient.exe. The problem is that I get an error:
Failed to add a service. Service metadata may not be accessible.
I added a mex endpoint in the config file but does not solve it:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="MyRest.Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint
address="XMLService"
binding="webHttpBinding"
behaviorConfiguration="restPoxBehavior"
contract="MyRest.IService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave" >
<!-- 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 for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
IService1.cs
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/Employees", ResponseFormat = WebMessageFormat.Xml)]
Employee[] GetEmployees();
}
[DataContract]
public class Employee
{
[DataMember]
public int EmpNo { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public string DeptName { get; set; }
}
Service1.cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
public Employee[] GetEmployees()
{
return new Employee[]
{
new Employee() {EmpNo=101,EmpName="Mahesh",DeptName="CTD"},
new Employee() {EmpNo=102,EmpName="Akash",DeptName="HRD"}
};
}
}
With WCF Restful service, do you actually need meta-data to expose service or to work on it? The answer is "NO". It's against the principles of Rest. Meta-data represents the interface(the operations), and for REST interface is fixed(http methods). WcfTestClient is for testing SOAP based Service(as they have to expose their interface through mex bindings).
Testing a RESTFUL service for http get could be vary easy. you just have to invoke it from your browser, using the URL. To test other http methods, you have to build your custom client.
If this seems a big task, then you could also use tools like Fiddler to build request data. An example could be seen here

aspNetCompatibilityEnabled="true"

I have made a Azure web app that has a ASP.NET web that also contains some JSON WCF services. I really don't know enough about WCF service models to be sure that I'm doing it right, does this look correct to you? Are there other service model configurations that is better for scalability, more maximum concurrent connections, etc?
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.net>
<settings>
<!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 -->
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
This works but I occasionally get unexpected connection drops (timeouts) with no HTTP error codes in my development environment which worries me.
Update # 24. Nov. 2011
web.config
<system.net>
<connectionManagement>
<!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 -->
<add address="*" maxconnection="48" />
</connectionManagement>
</system.net>
I'm suspecting that it may be the Visual Studio web server that causes the Ajax calls to get timeouts, after some minutes the service starts to accept requests again. Here is my complete setup, can you see what the problem is? I only have a single Ajax call to the service.
Inferface
IExample.cs:
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WebPages.Interfaces
{
[ServiceContract]
public interface IExample
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json)]
string GetSomething(string id);
}
}
ExampleService.svc.cs markup
<%# ServiceHost Language="C#" Debug="true" Service="WebPages.Interfaces.ExampleService" CodeBehind="ExampleService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
ExampleService.svc.cs codebehind
namespace WebPages.Interfaces
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExampleService : IExample
{
string JsonSerializeSomething(Something something)
{
var serializer = new DataContractJsonSerializer(something.GetType());
var memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, something);
return Encoding.Default.GetString(memoryStream.ToArray());
}
public string GetSomething(string id)
{
var something = DoSomeBusinessLogic(id);
return JsonSerializeSomething(something);
}
}
}
jQuery call from client
function _callServiceInterface(id, delegate) {
var restApiCall = "Interfaces/ExampleService.svc/GetSomething?id="
+ escape(id);
$.getJSON(restApiCall, delegate);
}
function _getSomethingFromService() {
_callServiceInterface('123',
function (result) {
var parsedResult = $.parseJSON(result);
$('#info').html(result.SomethingReturnedFromServiceCall);
}
);
}
Update
I think I know what the problem is now; it seems that WCF services are single threaed by default ( source: http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.SERVICEMODEL.SERVICEBEHAVIORATTRIBUTE.CONCURRENCYMODE);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true ) . That explain why my Ajax calls get timeouts, its blocked by another thread. This code should work a lot better:
ExampleService.svc.cs
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession,
IncludeExceptionDetailInFaults = false, MaxItemsInObjectGraph = Int32.MaxValue)]
//[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExampleService : IExample
web.config
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
</protocolMapping>
<behaviors>
<endpointBehaviors>
<behavior name="">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
ExampleService.svc
<%# ServiceHost Language="C#" Debug="true" Service="WebPages.Interfaces.TagService" CodeBehind="TagService.svc.cs" %>
Update # 9. Oct. 2011
I think I got the answer I needed here Locking with ConcurrencyMode.Multiple and InstanceContextMode.PerCall
aspNetCompatibilityEnabled="false" means not being able to access HttpContext, ASP.NET Sessions, etc. in my WCF code.
I think I got the answer I needed here Locking with ConcurrencyMode.Multiple and InstanceContextMode.PerCall
aspNetCompatibilityEnabled="false" means not being able to access HttpContext, ASP.NET Sessions, etc. in my WCF code.