I am creating a very basic WCF service with C# in Visual Studio 2010. I want to know if I can run my methods directly from a browser by typing something like: //localh
A straight answer. For GET Methods you can use a browser to view the result. FOR POST Methods you cannot use Browser, if you are directly pasting your url for post method. In order to achieve POST you can either create a HTML FORM or use FIDDLER to see the result.
Yes, you can call those methods in a browser, if your service is configured properly, though you have the URL syntax wrong.
To call WCF methods from a browser, you need to do two things:
[WebGet]
and [WebInvoke]
attributes on your methods, which you have done.Use a webHttpBinding
for the endpoint of your service and enable the webHttp
behavior. See http://weblogs.asp.net/kiyoshi/archive/2008/10/08/wcf-using-webhttpbinding-for-rest-services.aspx for a sample configuration, but the relevant parts are:
<service>
<endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="MyServiceContract" />
</service>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
Once that is done, WCF will start listening for URL request and route them to your appropriate web methods. You can set up URL templates in your WebGet
or WebPost
attributes that map URL segments to method parameters, if you want to make your URLs "cleaner", but that's optional. Otherwise, you pass parameters the same way you pass parameter to any other URL, using the parameter delimiter:
http://localhost:49815/MyService.svc/methodName?parameterName=value
Note that the default for a web-invoked method is a POST. Technically you can do these through a browser but it's much harder (you'd have to make a local HTML form, or use your Javascript console, or something similar), but the WebGet
methods can be invoked just by requesting the correct URL.
Also, if your methods return anything more complex than a string, WCF will try to serialize it as JSON; you may need to 'view source' on the resulting page to see it.
This does not answer your question, but it will make your life a lot easier to make your service RESTful (or REST-like). While you can do that with WCF, I'd strongly recommend taking a look at ASP.NET Web API.
There are also other alternatives available for creating RESTful services, such as Nancy or ServiceStack.