Posts
203
Comments
1118
Trackbacks
51
RESTful WCF Services with No svc file and No config

While Microsoft continues to add features to WCF with each version, they are also adding features that simplify working with WCF services as well. Historically WCF has been somewhat intimidating to the uninitiated because of the non-trivial configuration for endpoints including behaviors, bindings, and much more. For this reason, a lot of people stayed with “old school” asmx web services. With the new features of WCF 4, you can build powerful web services with *no* svc file and *no* endpoint configuration.

Building a RESTful WCF service in this way is quite easy and you don’t need rely on any item templates.  Just start with a blank asp.net web application project in Visual Studio. The web.config file is virtually empty:

   1:  <configuration>
   2:      <system.web>
   3:          <compilation debug="true" targetFramework="4.0" />
   4:      </system.web>
   5:  </configuration>

Next just add a regular C# class - for this example, I call mine PersonService and it will have basic CRUD operations. Typically we create interfaces in WCF to define our ServiceContract and operations like this:

   1:  [ServiceContract]
   2:  interface IPersonService
   3:  {
   4:      [OperationContract]
   5:      Person GetPerson(string id);
   6:   
   7:      [OperationContract]
   8:      Person InsertPerson(Person person);
   9:   
  10:      [OperationContract]
  11:      Person UpdatePerson(string id, Person person);
  12:   
  13:      [OperationContract]
  14:      void DeletePerson(string id);
  15:  }

Keep in mind, this step is *not* required. You *could* decorate your service class directly with these attributes and not even have the interface at all. However, in this case, it’s a nice convenience to encapsulate all the WCF attributes on the interface rather than your implementation class. The implementation of our PersonService class looks like this (I’ve removed the code that access the data store for brevity):

   1:  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   2:  public class PersonService : IPersonService
   3:  {
   4:      [WebGet(UriTemplate = "Person({id})")]
   5:      public Person GetPerson(string id)
   6:      {
   7:      }
   8:   
   9:      [WebInvoke(UriTemplate = "Person", Method = "POST")]
  10:      public Person InsertPerson(Person person)
  11:      {
  12:      }
  13:   
  14:      [WebInvoke(UriTemplate = "Person({id})", Method = "PUT")]
  15:      public Person UpdatePerson(string id, Person person)
  16:      {
  17:      }
  18:   
  19:      [WebInvoke(UriTemplate = "Person({id})", Method = "DELETE")]
  20:      public void DeletePerson(string id)
  21:      {
  22:      }
  23:  }

This is just a normal C# class that implement an interface. It’s also decorated with the typical WebGet/WebInvoke attributes (in the System.ServiceModel.Web namespace) that we use for RESTful services. Also notice that 3 of the 4 methods have the same UriTemplate but they are differentiated by the HTTP method (i.e., GET/PUT/DELETE). Also notice the AspNetCompatibilityRequirements attribute – this is needed for RESTful services that are processed in the ASP.NET pipeline as described here. You also have to add this to the config file (I know, I know – I said “no config” but I meant “no ugly WCF endpoint config”!):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:  </system.serviceModel>

So how do we take this regular C# class and make it into a service without an *.svc file?  The System.Web.Routing infrastructure has now been incorporated into WCF 4 to make this possible.  Just add the line of code (line #5) to your global.asax:

   1:  public class Global : System.Web.HttpApplication
   2:  {
   3:      protected void Application_Start(object sender, EventArgs e)
   4:      {
   5:          RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(PersonService)));
   6:      }
   7:  }

The WebServiceHostFactory makes RESTful services possible in WCF. The first parameter of my ServiceRoute constructor is an empty string which means that my URI of my service will hang right off of the root – this get combined with the UriTemplate defined in the WebGet/WebInvoke attributes.  So to get a person from my service, a URI would look like this:  http://mydomain.com/Person(21).  If I had specified “foo” instead of an empty string in the first parameters of the ServiceRoute constructor, then my URI would look like this:  http://mydomain.cmo/foo/Person(21).

That’s it!  You now have a fully functioning RESTful WCF service that you can fully test with Fidder for all HTTP verbs.

One interesting aspect to all this is that you can do all this in MVC as well. In fact, I typically do use MVC to return JSON to views for AJAX calls in my MVC apps. However, if you were building stand-alone services for this, would MVC be easier than the example of above? Keep in mind, we could simplify the example above even further by eliminating the IPersonService interface all together. I daresay that setting up RESTful routes like the ones shown above is easier with WCF than MVC (this, coming from an “MVC guy”) because we can apply the UriTemplates directly to the methods. To accomplish the same in MVC, you have to create custom route constraints to avoid the name of the C# methods from showing up in the URL (and honoring the REST HTTP verbs).  If you are going to do this, I really like the approach shown here. It’s a cool approach, but it’s *more* work than just doing it with RESTful WCF – no svc file and no configuration.

In fact, using the WCF infrastructure gets you even more features for free.  For example, if we add 1 more line of configuration (check out line #5 below) we get a help page and automatic format selection for free! Now our entire configuration just looks like this (and still no WCF endpoint configuration needed):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:    <standardEndpoints>
   4:      <webHttpEndpoint>
   5:        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   6:      </webHttpEndpoint>
   7:    </standardEndpoints>
   8:  </system.serviceModel>

Notice all we had to do to get the help page was the request “/help”:

wcf help page

The automatic format selection in WCF will honor the Accept header and/or the Content-type header and return XML, JSON, etc. to the caller based on the value specified in the header. Again, that takes custom code in MVC which you get for free in WCF.

posted on Saturday, August 21, 2010 9:17 PM Print
Comments
Gravatar
# re: RESTful WCF Services with No svc file and No config
Jay R. Wren
8/21/2010 10:56 PM
Best new ASP.NET based Service stuff I've seen since I first saw WCF. This is VERY cool.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Ravi R
8/24/2010 11:51 PM
Hey there Nice blog...
I just had a few questions about this. So basically its about how to deploy this service to IIS 7.0 and are their any other extra configuration settings to be changed. Or if I may ask has Microsoft showed the proper way to deploy this REST service?
Thanks

Regards,
Ravi
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
8/25/2010 12:02 AM
@Ravi - In the example above, there is nothing specific about REST to deploy to IIS. You can just deploy the the same as you would any ASP.NET web site you are deploying to IIS.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Nathan
9/26/2010 11:41 PM
Can you provide some 'official' links on this topic from like MSDN or MS team blogs? I'd like to dive a little deeper into it. Thanks.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
9/28/2010 7:14 AM
@Nathan - Here is a good starting point for you: http://msdn.microsoft.com/en-us/netframework/cc950529.aspx
Gravatar
# re: RESTful WCF Services with No svc file and No config
Simon Bastian
10/13/2010 3:50 AM
Hello, nice post, I also use this method as i think the configuring of endpoints in the web.config was a bit confusing.

I have a question, when i try to run this in IIS 7.5 with ssl i get this error:

Could not find a base address that matches scheme http for the endpoint with binding WebHttpBinding. Registered base address schemes are [https].

How do i change the service so it is able to run over https?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
10/16/2010 10:26 AM
@Simon - check out this example here: http://weblogs.asp.net/srkirkland/archive/2008/02/20/wcf-bindings-needed-for-https.aspx
Gravatar
# re: RESTful WCF Services with No svc file and No config
Will
10/19/2010 5:14 PM
Hi Steve,
Do you have any tips for this?
http://stackoverflow.com/questions/3970951/simple-url-routes-in-wcf-rest-4-0-without-trailing-slash

In your example, you only have one service (PersonService). But what if you wanted multiple services, but still wanted the nice short URLs.

Thanks,
Will
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
10/19/2010 9:15 PM
@Will - I posted my answer here: http://stackoverflow.com/questions/3970951/simple-url-routes-in-wcf-rest-4-0-without-trailing-slash/3974067#3974067
Gravatar
# re: RESTful WCF Services with No svc file and No config
Doug Stiers
11/8/2010 7:32 PM
Thanks, you saved me a lot of time. I've been using a RESTful API for some time and I really love how easily you can document and deploy an endpoint like this.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Amjad Nagrah
11/9/2010 1:29 PM
------------------------------------------------------------------------------------------------------------------------------------------
I am having a problem for the method:
[WebGet(UriTemplate = "Person({id})")]
public Person GetPerson(Int32 id)
{
}
The UriTemplate is expecting string type 'PersonID' but my database, model classes and repository defines this parameter as 'Int32'. Is there any way that, without me changing the whole code, instead this [WebGet(UriTemplate = "Person({id})")] accepts Int32 type variable.

Thanks/
Amjad
Gravatar
# re: RESTful WCF Services with No svc file and No config
james
11/11/2010 1:05 PM
Another great article, Steve.

For those following along, the Global.asax file the namespaces required are System, System.ServiceModel.Activation and System.Web.Routing;
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
11/14/2010 10:23 AM
@Amjad - This is a limitation of the current release. You have to use string and then Convert.ToInt32(id) inside your method. Note that request processor in the new Http stack (http://wcf.codeplex.com/) will allow you to have some of this functionality.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Bryan
11/30/2010 8:52 AM
Hi,

I'm having a hard time getting the PUT verb to work. Keep getting a 405 (method not allowed) error on IIS 7.5 on Windows 7 x64. Googled the heck out of this and everyone seems to tie this to WebDAV but I don't have that enabled on this machine. Any help would be appreciated.

Thanks!
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark
11/30/2010 9:30 AM
Hi Steve,
When trying to invoke a post request to my recreation of the example you have provided I am getting a 400 Bad request error from the service. After tracking in down I have concluded that the data is causing the issue.
<Person><Id>2147483647</Id><Name>Mike</Name></Person>
I have tried everything that I can think of but nothing is allowing me to post this data to the service.
Any help would be greatly appreciated.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
11/30/2010 2:34 PM
@Mark - Make sure you have your Content-type header set to "application/xml"
Gravatar
# re: RESTful WCF Services with No svc file and No config
Sankalp
12/18/2010 10:54 AM
Hi Steve, excellent article!! Just a quick question,. In the example above , in absence of config bindings and behaviours, what binding does it default to?
Second, Could you suggest ways to secure rest service operation. For example GetPerson in the current example.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
12/23/2010 12:07 AM
@Sankalp - Its the webHttpBinding. That is because the WebServiceHostFactory is used at start up so you know that's the binding it's using.

Check out OAuth or securing REST services. It's a big topic unto itself.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Stephen Patten
1/11/2011 9:31 AM
Steve,

Thanks for the post, the concepts work great, as I'm using your code in the wild. What troubles me is consuming the services from within SL4 using the HttpWebRequest/HttpWebResponse classes. Seems like changing the content type thows a ProtocalExecption. Can you provide a sample of how to consume this asynchronously?

Thank you,
Stephen
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
1/27/2011 8:35 PM
@Stephen - Can you be more specific on the error message? What content type do you want to use?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Stephen
2/5/2011 11:25 AM
Steve,

Problem(s) were solved, and there were a few of them, none the least being new to SL programing model.. Keeps the posts coming.

Regards,
Stephen
Gravatar
# re: RESTful WCF Services with No svc file and No config
Stephen Patten
2/5/2011 11:32 AM
Guess I do have one question though, why pass the ID and Person in this call

public Person UpdatePerson(string id, Person person)


Thank you.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
2/5/2011 3:45 PM
@Stephen - In this case, the first parameter is the variable that is used in the URITemplate and the second parameter is the HTTP request body. So in a way, you're doing it to keep the URL looking proper even if you could get the id from the object itself. The new WCF Web APIs (wcf.codeplex.com) have some new functionality to make this a little more elegant.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Denis Castanheira
2/7/2011 11:25 AM
Hi Steve!
Perfect post!
I am trying to publish on IIS 5.1 (Windows XP Professional), but, I get error 'HTTP 404 - File not found'.
Do you have any idea to resolve this?
Thank you.
Denis
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
2/7/2011 4:59 PM
@Dennis - Without seeing the details of the UriTemplate you've specified in code and the URI you're trying to hit, it's tough to troubleshoot. Are you saying that it's working when you run it from Visual Studio web server but does *not* work when you run from IIS?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Jessica Fitch
2/10/2011 7:02 PM
Hi Steve,
Any known issues with XML serialization using this approach versus creating an ASMX web service? In particular I am trying to resolve issues with inheritance. To use your example, I would like to create an Employee subclass of Person. I would then like to be able to return an instance of Employee (or Customer or another type of Person) without the system encountering a serialization exception. It would also be nice if it were possible to POST/PUT Employees and Customers in addition to plain old People. Attempting to play around with XmlInclude hasn't yielded operational results for me. Any pointers?
Thanks,
Jessica
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
2/10/2011 7:09 PM
@Jessica - Decorate your Person class with [KnownType] attribute specifying the sub-classes - http://www.freddes.se/2010/05/19/wcf-knowntype-attribute-example/
Gravatar
# re: RESTful WCF Services with No svc file and No config
Jessica Fitch
2/11/2011 1:00 PM
I was able to get the [KnownType] to work with a basicHttpBinding, but not webHttpBinding. I will freely admit that I'm a newcomer to .NET and may be doing something highly incorrect, but it seems as though exposing the same method via the two different endpoint types (the method being double decorated with OperationContract and WebGet) I should be able to get the correct output rather than a serialization exception. What I found instead is the ServiceKnownType attribute (http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceknowntypeattribute.aspx#Y1254) which worked beautifully with the WebGet. I hope this helps others. Alternatively I would love to hear guesses as to what might have been going wrong if KnownType is still believed to be sufficient for a webHttpBinding endpoint.
Jessica
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
2/11/2011 3:20 PM
@Jessica - Nope, I think I'm simply pointed you to the wrong attribute. :) Looks like you got it now.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Tris Setiawan
2/22/2011 11:33 PM
hi Steve,

nice post, i have mine work with development server but not with IIS 7.0 on win7, maybe its the same issue as Denis, any idea how to solve this?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Rob Banning
2/23/2011 11:49 PM
@Denis & @Tris

I has a similar problem and found my solution here:

http://stackoverflow.com/questions/4793127/404-when-running-net-4-wcf-service-on-iis-no-svc-file

Hope it helps!
ROB
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mike Horton
4/29/2011 6:01 PM
This may seem like a silly question but how can you debug the service? I've got mine setup where it's not throwing an error but when I go to parse through the ArrayList I've returned in jQuery/ajax it says that the returned value is null.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
4/29/2011 10:40 PM
@Mike - I presume you're doing a get request and returning your data? Did you try just hitting the URL in a browser or Fiddler?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mike Horton
5/1/2011 10:56 PM
Thanks for replying Steve....

I've tried both post and get. Initially I was just going through my app but I did figure out how to go straight from my browser. The example for the Json body is "anyType":null so that's where I'm stuck. With a WCF Service Application I could step through code using break points. I'm don't know who to do something similar with your setup.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
5/10/2011 8:58 PM
@Mike - You lost me on the Json body. Let me know if you want me to look at the code from dropbox or something.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Bala
6/3/2011 1:52 AM
Hi,

I tried the above article and everything went fine except, I'm not getting any JSON data on the help page or in JQuery call.

I created two properties for Person (Id, Name) and the rest are same as yours. Below is what showing up on the "Help" page. (xml also displays just the root line).

------------
The following is an example request Json body:

{

}
----------

Any idea of what am doing wrong here?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Abhishek
8/10/2011 12:03 AM
Can we do this in framework 3.5 where ServiceRoute is not supported. is there a way to add a route in 3.5
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
8/14/2011 2:02 PM
@Abhishek - I'm not aware of a way to do this with the out-of-the-box features of 3.5.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Ed
8/22/2011 11:58 PM
Not working in json object...
Gravatar
# re: RESTful WCF Services with No svc file and No config
far
8/23/2011 9:10 PM
Where can i find source code of this?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
8/24/2011 9:31 AM
@far - 100% of the source code is contained in the blog post.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Christian
8/31/2011 6:27 PM
Worked perfectly. Thank you!
Gravatar
# re: RESTful WCF Services with No svc file and No config
Phil
9/1/2011 10:10 PM
Great post. I have a question on receiving json post from an ios app. How is this done. Does the ios device send an object that is the contract or in this case a Person
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
9/5/2011 2:37 PM
@Phil - Regardless of the consumer (iOS or otherwise), the consumer would send a wire format (xml or json in the example above) that is supported by the service. So yes, an xml representation of the Person in the example above.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Kev Gibson
9/10/2011 2:10 AM
Good clear article...but I have a question about deployment. I stated with a simple WCF REST app like above developed in Visual Studio 201. Runs locally fine.
If I use DEPLOY to the root directory of the web sit it runs fine also. But we are moving into a multi programmer project and would like to deploy several services into sub folders/application folders so that web config and global asax files do not overwrite each other.
When I deploy to site/application folder service does not run..any idea how we run from folders

Cheers Kev
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
9/18/2011 10:36 PM
@Kev - It's really difficult to diagnose why your services are not running without more information. Did you set up virtual directories? Did you get any error messages? Did you look at IIS logs, etc.? I'd need a lot more diagnostic information to help I think.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Eric
9/30/2011 2:03 AM
This is a great example! Everything works perfectly, but testing in my browser (Chrome, IE, Firefox, and Safari) seems to always return the content-type text/html. When making an XmlHttp request, it returns application/xml correctly. Is there an easy way to get WCF to NOT return text/html?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
10/3/2011 5:40 PM
@Eric - Use Fiddler and specify the Accept header of your choice.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Tim
10/14/2011 11:27 AM
How will this example change if you are using the new WebApi framework (version 0.50 when this comment was sent)? For example, using the new classes WebApiRoute and HttpServiceHostFactory when adding routes to the RouteTable collection.

Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
10/14/2011 11:32 AM
@Tim - the current release of the Web API doesn't look *that* much different than the above. But if you have a look at http://webapiscaffolding.codeplex.com/ you'll see examples. Ultimately, the hope is the the Web API team fully incorporates into routing much like MVC.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Pat
10/14/2011 4:16 PM
This is exactly what I was looking for. I just needed something basic to build off.
When I call the service I get a 200 result back when I return null. But when I return a person with properties I get a 504. What's going on in the person?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve
10/18/2011 10:00 AM
@Pat - A 504 is a Gateway timeout. It seems like you have something environmental going on. Hard for me to know without seeing the solution.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Allan
10/23/2011 3:35 AM
This worked on my dev machine on VS web server and IIS express, but when I moved the application to server running IIS, I just got http 404 when requesting the urls.

Make sure you add

<modules runAllManagedModulesForAllRequests="true">
</modules>

to web.config, works for me! :-)
Gravatar
# re: RESTful WCF Services with No svc file and No config
Paria
11/24/2011 7:47 AM
This works fine for me. But my xml values are half loaded. Other values are not getting loading . how do I mention the size of the xml file that i am streaming.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
12/4/2011 7:09 PM
@Paria - I don't follow the question. Can you give me an example what you mean?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Uri London
12/11/2011 9:44 AM
GET is working great
Any other method doesn't work. I'm not sure I compose the request correctly. Using Fiddler RequestBuilder.

Also, I can I get a detailed error message?

Also, what do I need to do to get Json asnwer? With the Fiddler's RequestBuilder, I'm setting 'Accept' header to application/json. I that the correct method?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
12/12/2011 8:52 AM
@Uri London - Hard to diagnose your problem based on the information you've provided. In terms of formulating the requests in Fiddler, this blog post has a video at the end which shows that in action: http://geekswithblogs.net/michelotti/archive/2011/04/21/wcf-web-api-is-pure-simplicity-with-nuget.aspx.

What is the specific behavior you're seeing when using verbs other than GET? Are you getting a 404? If so, check out this post: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx
Gravatar
# re: RESTful WCF Services with No svc file and No config
John B
12/14/2011 2:41 PM
Steve, excellent article. I got XML/JSON responses working, and with a little extra tinkering I got basic authentication and custom HTTP responses to work as well.

One extra credit question for you: is it possible to add a discoverable WSDL endpoint (the third part of the "big 3": XML,JSON,WSDL) using this technique? Meaning, classes can be generated by third parties with the "svcutil.exe" tool and used with SOAP.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark Jones
1/6/2012 2:03 PM
Great post... very helpful. I was able to get everything to work except the "/help". How/where is the response to /help implemented? Thanks again for the post...
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
1/11/2012 9:04 AM
@Mark - Make sure you have helpEnabled="true" as shown in the config file above.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Kavitha
1/14/2012 1:56 PM
Hello, Great Post Steve!
I've developed REST service in the same lines and deployed in IIS Successfully.

How can I consume this in my traditional ASP.NET class library/web application? Do I need to create a proxy? Can you please provide a sample/link if you've? Appreciate your help.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
1/17/2012 4:04 PM
@Kavitha - You don't create a proxy in the same way as you would with a SOAP service. Typically you use the HttpClient and handle the serialization however you desire: http://msdn.microsoft.com/en-us/library/f3wxbf3f(v=vs.80).aspx
Gravatar
# re: RESTful WCF Services with No svc file and No config
jagadeeshwar
1/31/2012 2:45 AM
i am consuming the rest service by jquery ajax call as below.

function CallService() {
$.ajax({
cache: false,
async: false,
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
//data: varData, //Data sent to server
//contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
//debugger;
ServiceSucceeded(msg);
//alert(msg);
},
error: ServiceFailed// When Service call fails
});
}

function GetPageById() {
//debugger;
varType = "GET";
varUrl = "http://revalapidev.revalweb.com/PageInfo/GetPageById?PageId=1&CompanyId=1&SiteId=1";
//varUrl = "http: //localhost/RevalAPI/PageInfo.svc/GetPageById";
varContentType = "application/json; charset=utf-8";
varDataType = "json";
varProcessData = false;
//varData = '{"PageId": "' + $('#txtPageId').val() + '","CompanyId": "1", "SiteId":"1"}';
CallService();
}

i am connecting to the DB which i have checked with profiler. but getting result as null and result status as unknown
Gravatar
# re: RESTful WCF Services with No svc file and No config
Collin
2/8/2012 9:10 PM
I seem to run into this error when I try to build this demo locally:

"Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'"

Any ideas why I am getting this, can't seem to find out much about it.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
2/10/2012 8:59 AM
@Collin - The error is pretty self-explanatory in this case. That scenario is not supported. WebScriptEnabled has fallen out of favor these days - there are other good mechanisms for JavaScript client support. Just use jQuery.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
2/12/2012 9:59 PM
@jagadeeshwar - Hard to tell what's happening with this information you've provided. Is this a cross-domain call?
Gravatar
# how to consume wcf RestFul service on MVC3
jecky
2/23/2012 12:03 PM
I am first time trying to consume wcf RestFul service on MVC3. I have services such as http://Service/Login (for login) & http://Service/Registration (for registration). The service will receive and return data in json format. But I don't know how to call them in MVC3 project and implement it best way. Any help with this is appreciated.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Salil
3/3/2012 10:52 AM
I am trying to consume a JSON file returned by Restful WCF Service, but having issues.
The details can be found at the link,
http://stackoverflow.com/questions/9546338/unable-to-return-json-string-from-wcf-service-from-jquery

Please let me know what I am missing.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Wenbiao
3/12/2012 6:43 PM
Hi, I tried this method (it is very similar to the VS 2010's Online template, "WCF REST Service Template 40(CS)"), and it worked fine for my localhost. I can get the results back from "http://localhost:12345/MyService/myuri" for example.

However, if I tried to use the IP address of my localhost, e.g. http://192.168.1.83:12345/MyService/myuri, it will fail.

I got Http 502,
"[Fiddler] Connection to 192.168.1.83 failed.<BR>Exception Text: No connection could be made because the target machine actively refused it 192.168.1.83:12345"

My firewall is off. What can cause this problem?

Thanks!
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
3/14/2012 8:50 PM
@Wenbiao - When it was working, were you running from Visual Studio web server or IIS? This is an environmental thing so not easy to diagnose because it could be lots of things. It literally means no services are listening on that port.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Gary Blakely
3/28/2012 6:47 PM
I've read over 20 articles on how to do wcf rest services. This explains the "whys" better than the rest but like the rest it does not approach the subject of deployment to an existing large, mature, .net 4.0 IIS website.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
3/28/2012 6:53 PM
@Gary - Not 100% sure I'm following the specifics of your question. You can just deploy with WebDeploy or any deployment methodology of your choice (xcopy?).
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark Kamoski
4/25/2012 2:38 PM
I am getting an "endpoint not found" run time error. I followed the example very close but it does not work. Can you help?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Venkatesh Manoharan
4/27/2012 5:18 PM
Mark - Can you check whether your web.config file looks good?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark Kamoski
5/3/2012 11:16 AM

Dear Steve-A-Reno --

You are awesome!!!

I got it working.

You know what the issue was???

Right, a "small thing".

Instead of this incorrect URL...

http://localhost:55389/help/

...I had to use this correct URL...

http://localhost:55389/help

...and the "rest" is history in the making.

Thanks so much.

-- Mark Kamosk
i

Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark Kamoski
5/14/2012 4:43 PM
Dear Steve -- Please help. Cannot get POST to work for creating an object. Can you show some sample code from the call-site site in a WebApp ASPX page. Please. Thanks. -- Mark Kamoski

Gravatar
# re: RESTful WCF Services with No svc file and No config
Mark Kamoski
5/15/2012 10:09 AM
I think my POST data is getting built and sent correctly but I cannot figure out how to get the POST data out the the HttpContext.Current.Request on the "catching" side, in the Rest service itself. Can you help?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Aruna
8/27/2012 6:17 PM
Thank you !! Excellent article used it. Saved loads of time.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Aruna
8/28/2012 4:41 PM
If any of you want to return valid error messages from the service. This will work with the above code.

WSErrorMsg errdetail;
errdetail.code = "001";
errdetail.message = "Do not have any account numbers";

throw new WebFaultException<WSErrorMsg>(errdetail, System.Net.HttpStatusCode.Forbidden);

( you can specify ResponseFormat = WebMessageFormat.Json or any other formatting you need in WebGet)
Gravatar
# re: RESTful WCF Services with No svc file and No config
Gene
9/29/2012 5:00 PM
I don't think I am getting the XML back the way others are. Here is what I get...

<Person xmlns="http://schemas.datacontract.org/2004/07/Test" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><_x003C_Coordinates_x003E_k__BackingField>[1,2,3,4]</_x003C_Coordinates_x003E_k__BackingField><_x003C_Id_x003E_k__BackingField>16</_x003C_Id_x003E_k__BackingField><_x003C_Name_x003E_k__BackingField>Little Rascals</_x003C_Name_x003E_k__BackingField></Person>

My Person class contains three properties ... Id, Name, Coordinates.

What am I doing wrong?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Gene
9/29/2012 5:19 PM
Figured it out. I add my Person class decorated with the "Serializable" class. When I removed that everything worked as expected. What do I have to do if I want it to make it Serializable AND use it in the maner described above?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Gene
9/29/2012 5:33 PM
Never mind...figured that one out also...I can decorate the Person class with both Serializable and DataContract.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Alex
10/29/2012 12:42 AM
Hi,
Thank you for great article.
One problem. When I run the service on IIS 7.5 and use PUT then I receive 405 - Method not allowed. The problem is in WebDAV. I remove WebDAV like this:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>
and receive 404 - File not found ;(
POST works great.
Any suggestions?
Alex
Gravatar
# re: RESTful WCF Services with No svc file and No config
Steve Michelotti
10/29/2012 10:03 AM
@Alex - try this: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx
Gravatar
# re: RESTful WCF Services with No svc file and No config
Alex
10/29/2012 11:13 PM
Thank you. It helps.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Hemant
11/16/2012 9:33 AM
When i pass XML content i get bad request error. It works if it is a string. here is sample of request I would be passing
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><request><account>2323</account></request></string>

Appreicate your help.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Aruna
12/7/2012 3:59 PM
@Hemant, not sure if this helps. When I received bad request when POST deserialized to person object, I used the following. Accept incoming stream as it is JSON or XML and then do whatever u need to do with it within the method. So you can see if incoming XML is not formed or whatever error may be....
[WebInvoke(UriTemplate = "Person", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)]
public Person InsertPerson(Stream JsonStream)
{ .. use json.net or object serialization to convert json stream - so you have better error handling}

I use JSON you can specify the content to be XML and handle that XML string instead of JSON.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Manikandan
12/28/2012 11:07 PM
After a fair amount of struggling I was able to successfully deploy a WCF 4.0 REST web service on XP/IIS5. For the benefit of you and others in the same situation, here's what I did (let me know if you need more detail):

1.Using VS 2010, build a deployment package for the project and then install it on the target machine (your web server). The following link will show you how to do this: http://vishaljoshi.blogspot.com/2009/03/web-packaging-installing-web-packages.html

2.Make sure that your virtual directory in IIS is configured to use .NET 4 (right click on virtual directory > properties > ASP.NET tab > ASP.NET Version)

3.Configure your virtual directory to support extensionless requests (i.e. your REST API) by creating a wildcard mapping (right click on virtual directory > properties > configuration > mappings tab) with the following properties:
Executable: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Extension: .*
Check that file exists: unchecked
(Note: watch out for the bug that keeps the "OK" button on this dialog grayed out. To get around this just click in the executable textbox after entering your extension and the "OK" button should get enabled).

4.If you get an authentication error when accessing the service then turn off integrated authentication on the virtual directory. This should fix the problem if you have used the defaults in the generated web.config of your service. If you have explicitly modified the authentication mode then you will have to adapt accordingly.


Thanks fo BitMask who found the above solution
http://stackoverflow.com/questions/3990325/deploy-wcf-rest-4-0-to-xp-iis-5
Gravatar
# re: RESTful WCF Services with No svc file and No config
Satyen
4/29/2013 3:08 AM
Hi,
I have created REST WCF Service Application using .net 4 and now want to host it on IIS 7. Can any one please guide me in this ? I have tried but no success.
thanks in advance.
Gravatar
# re: RESTful WCF Services with No svc file and No config
chitranjan
5/6/2013 4:53 AM
I f you want to get more example related to WCF Restful service then use this link and download all source code
http://www.dotnetnukes.blogspot.in/2013/04/create-restful-wcf-service-api-using.html
http://www.dotnetnukes.blogspot.in/2013/05/basic-step-by-step-wcf-webservice.html
Gravatar
# re: RESTful WCF Services with No svc file and No config
Zeeshan
5/30/2013 10:15 AM
I have used your approach but i have defined two services instead of one like below:
RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(StoreService)));
RouteTable.Routes.Add(new ServiceRoute("Service2", new WebServiceHostFactory(), typeof(SurveyService)));

when i try to access the service in browser it gives following error:

A binding instance has already been associated to listen URI 'http://localhost:53456/CashAPP/store'. If two endpoints want to share the same ListenUri, they must also share the same binding object instance. The two conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of AddServiceEndpoint() and config

Can you please help? this is URGENT.
Gravatar
# re: RESTful WCF Services with No svc file and No config
J Tyler
6/11/2013 7:17 PM
(I’ve removed the code that access the data store for brevity)

Q. Can you post all the code?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Pedro Loaiza
7/10/2013 12:48 AM
This is a great solution. I was able to implemented right to load xml files. The only problem is that if the file is larger than 64KB I get a 400 error. I have added the follwoing in my web.config:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2097151" />
</system.web>

and also
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="524288000"/>
</requestFiltering>
</security>
</system.webServer>

but I still get the 400 Bad Request for large xml files. How can I get over this limitation?

Thanks
Gravatar
# re: RESTful WCF Services with No svc file and No config
huhu
7/11/2013 12:12 AM
I wish to implement a basic authentication with username and password validator:
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Ezypay.Wcf.Security.LoginValidator, Ezypay.Wcf"/>
</serviceCredentials>

How can i configure this in web.config ?
Gravatar
# re: RESTful WCF Services with No svc file and No config
Milos
8/12/2013 5:39 AM
Hi,

This is a great article.
I am wondering is it possible to make cross-domain call with this kind of implementation (without end-points)?
How I need to expand my service to work with JSONP?
I did it with implementation which include end-points (crossDomainScriptAccessEnabled="true"), but I do not know how to do that here?.

Thanks,
Milos
Gravatar
# re: RESTful WCF Services with No svc file and No config
Emerson
12/24/2013 1:51 PM
Hi,

Great article, thanks a lot...
How I can publish the services in a production environmet???

Thanks,
Emerson
Gravatar
# re: RESTful WCF Services with No svc file and No config
Gus
2/20/2014 8:03 AM
Hi, it worked ok on W8 IIS8, but when I deployed on W2K8 IIS7.0 I got 404.0 error.
Tried a lot of things (aspnet_regis, ServiceSvcRegis.exe, repair ASP.NET from control panel, etc), but what really solved my problem was this hotfix: http://support.microsoft.com/kb/980368

Also, to get Json response, had to change to "false" this web.config property: automaticFormatSelectionEnabled

Thanks for your article.
Gravatar
# re: RESTful WCF Services with No svc file and No config
Ed
5/15/2014 12:39 AM
I have very similar services (no svc) 4.0
On my dev server running in vs 2010 I can post all day long.
Once I deploy to IIS All POSTS fail with 400 bad request. Gets work fine. Its not a client problem, I'm using the same client to call both.
IIS Trace is very ambiguous ModuleName=”ManagedPipelineHandler”, Notification=”EXECUTE_REQUEST_HANDLER”, HttpStatus=”400″, HttpReason=”Bad Request”, HttpSubStatus=”0″, ErrorCode=”The operation completed successfully"
the xml request is not very large, under 1k

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud