I'm new to WCF Web Services. I'm trying to test my simple hello world web service.
For now, I'm doing self hosting. I'm at the point where I've started the host application, opened my browser and typed in the address to my resource. I've also run Fiddler and created a Request by using the Composer. In both cases, I get the "You have created a service." page that has a link to my .wsdl.
I was expecting to see the "Hello World" text in my Response or a web page that has "...Hello world".
What am I missing? or am I just misunderstanding the process?
App.Config
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="My.Core.Services.GreetingService" behaviorConfiguration="MyServiceTypeBehaviors">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/greeting"/>
</baseAddresses>
</host>
<endpoint name="GreetingService" binding="webHttpBinding" contract="My.Core.Services.IGreetingService"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Host code
using System;
using System.ServiceModel;
using My.Core.Services;
namespace My.Service.Host
{
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(GreetingService)))
{
host.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
host.Close();
}
}
}
}
Hello World Contract and Service
using System.ServiceModel;
using System.ServiceModel.Web;
namespace My.Core.Services
{
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet(UriTemplate = "/")]
string GetGreeting();
}
}
using System.Collections.Generic;
namespace My.Core.Services
{
public class GreetingService : IGreetingService
{
public string GetGreeting()
{
return "Greeting...Hello World";
}
}
}
If I understand you correctly, you can see your wsdl link at the following url
http://localhost:8080/greeting
In order to now call your endpoint, you need to add it to the url like this
http://localhost:8080/greeting/GetGreeting/
I'm not entirely sure why you have the UriTemplate thing in there though other than my guessing that you probably just copy pasted it from an example. Unless you have specific query string parameters that you want defined, you don't really need it and it kind of tends to complicate things so I'd recommend taking it out. That means your Interface would look something like this...
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet]
string GetGreeting();
}
...and you can then lose the final "/" on the url.
I figure out the problem. When I use the url: "http://localhost:8080/greeting" the server sends the temp page. When I add the backslash "/" on the end of the url it execute my service.
so, "http://localhost:8080/greeting/" works and sends me the "...Hello World" back.
Related
I'm desperately in need of a working example of a WCF 4 RESTful web service. Our SaaS ticketing system (zendesk.com) can communicate with an URL target using HTTP GET, POST or PUT. I have not done any web related work (only c# console apps) but have now been tasked to create a WCF 4 web service with the following requirements:
Secured via HTTPS
Secured via username / password
Read and process the data from the SaaS system that is transmitted as application/x-www-form-urlencoded information, for example:
http://somedomain/a/path?value=message+with+placeholders+evaluated
My current code is as follows:
namespace WcfService2
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke]
void ClearAlert(Stream input);
}
}
namespace WcfService2
{
public class Service1 : IService1
{
public void ClearAlert(Stream input)
{
StreamReader rawTicketData = new StreamReader(input);
string ticketData = rawTicketData.ReadToEnd();
rawTicketData.Dispose();
//Do some work with ticketData
}
}
}
The web.config file:
<services>
<service behaviorConfiguration="MetaDataBehavior" name="WcfService2.Service1">
<endpoint behaviorConfiguration="RestBehavior" binding="webHttpBinding" bindingConfiguration="" name="REST" contract="WcfService2.IService1" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<behaviors>
I am currently using only HTTP (not HTTPS) for development and testing hence the missing binding entry / entries for HTTPS as well as any entries for login purposes in the web.config, at least I assume that is what / where I need to add the needed configuration but again, I have no knowledge.
I would more than appreciate any help / assistance I can get in creating a web service with the three above described requirements.
Thanks to all!
William
When using WCF, there is a section in the web.config as below.
<system.serviceModel>
<services>
<service name="abc">
<endpoint /> <---this
</service>
</services>
</system.serviceModel>
Is it possible to edit the area I've marked programmatically?
I can see there is a sytem.serviceModel namespace, but other than that I'm a bit lost.
If you want to change these parameters at runtime you can override ServiceHost.OnOpening()
E.g. to change port:
protected override void OnOpening()
{
foreach (ServiceEndpoint endpoint in Description.Endpoints)
{
string uriString = string.Format("{0}://{1}:{2}{3}",
endpoint.Address.Uri.Scheme,
endpoint.Address.Uri.Host,
endpoint.Address.Uri.Port + _basePort,
endpoint.Address.Uri.LocalPath);
endpoint.Address = new EndpointAddress(uriString);
}
base.OnOpening();
}
To complement Mike Mozhaev's answer, since your service is hosted in IIS you'll need a ServiceHostFactory to get a reference to the service host (or to use your own host). There's some information about it at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx.
I tried hosting a WCF Library service with windows service project, I installed the service, however, when i start the service in services.msc, the service start and closses immediatly. Following the message that gets displayed:
The Servicel service on Local
Computer started and then stopped.
Some services stop automatically if
they are not in use by other services
or programs.
The App.config file for wcf and the windows service project is same and it is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="WorkMateWCF.Service1">
<endpoint address="" binding="netTcpBinding" bindingConfiguration=""
contract="WorkMateWCF.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8523/WorkMate1" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The entire project/solution is downloadable here: https://skydrive.live.com/?cid=d358d316fa2c3a37&sc=documents&uc=1&id=D358D316FA2C3A37%21135#
Could you please guide me on how to proceed further. Thank you.
Additional information:
Following is the code from the service1.cs file in windows service project.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using WorkMateWCF;
namespace WorkMateWinService
{
public partial class Service1 : ServiceBase
{
internal static ServiceHost MyServiceHost = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (MyServiceHost != null)
{
MyServiceHost.Close();
}
MyServiceHost=new ServiceHost(typeof( Service1));
MyServiceHost.Open();
}
protected override void OnStop()
{
if (MyServiceHost != null)
{
MyServiceHost.Close();
MyServiceHost = null;
}
}
}
}
What I find very confusing (and probably the .NET runtime, too) is the fact that your Windows Service is called Service1, while your WCF Service also is called Service1 (without a namespace or anything).
So which of the two Service1 class types will be used here???
MyServiceHost = new ServiceHost(typeof(Service1));
I'm not sure - and I'm afraid it will be the wrong class (the Windows NT Service class).
You should give your stuff more meaningful names and keep those things apart (by name, too) !
Got the issue, when I reviewed my event logs I found this:
"Service cannot be started. System.InvalidOperationException: The HttpGetEnabled property of ServiceMetadataBehavior is set to true and the HttpGetUrl property is a relative address, but there is no http base address. Either supply an http base address or set HttpGetUrl to an absolute address.
at System.ServiceModel.Description.ServiceMetadataBehavior.EnsureGetDispatcher(ServiceHostBase host, ServiceMetadataExtension mex, Uri url, String scheme)
at System.ServiceModel.Description.ServiceMetadataBehavior.CreateHttpGetEndpoints(ServiceDescription description, ServiceHostBase host, ServiceMetadataExtension mex)
at System.ServiceModel.Description.ServiceMetadataBehavior.ApplyBehavior(ServiceDescription description, ServiceHostBase host)
at System.ServiceModel.Description.ServiceMetadataBehavior.System.ServiceModel.Description.IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescript..."
Then after thorough reviewing, the issues is that I did HTTPSGETENABLED to false only for one, infact there are two, after making the change for the other one, the app started to work like charm.
I special
I’m trying to run a very basic web service on the same IIS7 website that runs a MVC2 application. This is presenting a couple of different issues, and I believe it has to do with my system.serviceModel, but obviously I don’t know for sure (or I would fix it).
On the server side I can run my service just fine, the help operation works like a charm. I can execute the default WCF operation GetData and supply a value through the FireFox address bar.
http://localhost/services/service1/getdata?value=3 (example)
The first problem I’m having is that when I navigate to the base service URI it will display the message below. While this isn’t the end of the world because I can still execute code by manipulating the address; I do expect something else to be displayed. I expect the standard new web service message explaining that by appending “?wsdl” to the address you will receive the auto generated WSDL. I cannot access my auto generated WSDL.
“Endpoint not found. Please see the
service help page for constructing
valid requests to the service.”
Problem number two is in regard to client applications connecting to my web service. I created a console application in separate Visual Studio solution and added a web service reference to Service1. In the Visual Studio tool I can see and use the two methods that exist in my service, but when I run the code I get the following exception.
InvalidOperationException Could not
find default endpoint element that
references contract
'ServiceReference1.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.
Before I post my code (I’m sure readers are tired of reading about my struggles) I do want to mention that I’ve been able to run a WCF Service Library and Console application in the same solution flawlessly. There seems to be very few resources explaining WCF, WCF configuration, and working with MVC. I’ve read through several articles and either they were out-of-date or they were so simplistic they were nearly useless (e.g. click button receive web service named “Service1”).
To summarize; why am I not able to access the auto generated WSDL and how can I successfully connect my client and use the web service? Now the best part; the code.
Global.asax
//Services section
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
Web.Config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="DefaultEndpoint" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
<mexEndpoint />
</standardEndpoints>
<services>
<service name="Project.Services.Service1" behaviorConfiguration="MetadataBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" /> <!-- httpGetEnabled="true" does not solve the problem either -->
<!-- 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>
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET")]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
Service1
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Client Program
class Program
{
static void Main(string[] args) {
Service1Client client = new Service1Client();
client.GetData(2);
}
}
Thanks for the help! The problem was inside of my Global.asax.cs.
Original:
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
New:
routes.Add(new ServiceRoute("services/service1", new ServiceHostFactory(), typeof(Service1)));
The difference was chaing the host factory from "WebServiceHostFactory" to "ServiceHostFactory".
The second part of my question regarding client connections is because configuration settings are not being generated. I have to manually type them for each client. Yikes!
To avoid manually typing client configuration I had to change my endpoint
Original
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
New
<endpoint binding="wsHttpBinding" contract="Project.Services.IService1" />
After making this change the service and client are working flawlessly.
A quick answer to one of your questions:
To summarize; why am I not able to
access the auto generated WSDL
<serviceMetadata httpGetEnabled="false" />
...needs to be
<serviceMetadata httpGetEnabled="true" />
...in order to be able to retrieve the WSDL over http. You have to tell WCF to generate service metadata, and you've told it not to.
My system is Windows 7 Ultimate 32 bit. Running Visual Studio 2010 beta 2 targeting .Net 4.
I have a project containing service contracts.
A project containing the services.
And an ASP.NET Web Application that is hosting the services in IIS.
I've written my own Clients using the ChannelFactory().CreateChannel()...
Whenever I run my application that uses the ServiceClient and calls a method on the service, I get this error:
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)
I've tried to add a service reference in VS, so that the service client is auto-generated and that doesn't change anything.
Then I tried to create a new WCF Service Application from the Web category in VS2010, adding a service reference and calling the standard GetData method That works fine, so it is for sure my service or the hosting of the service that goes wrong...
UPDATE
I noticed that this error was only present when using wsHttpBindings. basicHttpBindings works fine.
This is how I instantiate the service:
private IAdminService _AdminService;
public AdminServiceClient()
{
_AdminService = new ChannelFactory<IAdminService>(String.Empty)
.CreateChannel();
}
Client config settings:
<system.serviceModel>
<client>
<endpoint address="http://AdminServices/svcs/AdminService.svc"
binding="wsHttpBinding"
contract="MyApp.Admin.Model.ServiceContracts.IAdminService" />
</client>
</system.serviceModel>
My service looks like this:
public class AdminService : IAdminService
{
public User GetUserByEmail(string email)
{
throw new NotImplementedException();
}
public void CreateUser(string fullname, string email,
string encryptedPassword,
string encryptedPasswordQuestion,
string encryptedPasswordAnswer)
{
throw new NotImplementedException();
}
public IEnumerable<Application> GetApplications()
{
IEnumerable<Application> apps = new List<Application>();
// Call data access layer method to retrieve Applications
return apps;
}
public IEnumerable<ApplicationInstance> GetApplicationInstances(
long? applicationId)
{
throw new NotImplementedException();
}
public Dictionary<string, string> GetApplicationsAndInstances()
{
Dictionary<string, string> appsAndInstances =
new Dictionary<string, string>();
appsAndInstances.Add("Dummy 1", "1");
appsAndInstances.Add("Dummy 2", "2");
return appsAndInstances;
}
}
My AdminService.svc file looks like this:
<%# ServiceHost Service="MyApp.Admin.Services.AdminService" %>
My Service Host config looks like this:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"
targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="MyApp.Admin.Services.AdminService">
<endpoint address=""
binding="wsHttpBinding"
contract="MyApp.Admin.Model.ServiceContracts.IAdminService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I've also tried to create a new Console App, and add a service reference to http://AdminServices/svcs/AdminService.svc - that doesn't work either.
I've added AdminServices to my hosts file, and I can browse http://AdminServices/svcs/AdminService.svc and see the service information...
The most obvious cause would be that you are loading a 64 bits DLL into a 32 bits process or visa versa. However given that you are running everything on a a 32 bits development box I assume this isn't the case.
The other option is a .NET bug using a generic constraint like this:
public class SpecificClass: BaseClass: where T : class { }
If you remove the where T : class it should work just fine.