What framework to use for RESTful Services in .net - c#

I know that similar questions have been asked, but most of them are out of date. So here we go again :). I need to implement a complete REST service layer for our application. The problem that i have is which framework would be the best to solve this problem. I just need a nice framework that lets me focus on the problem and not on the REST or whatever is required. Authentication is a required feature. Here are some of my ideas; what do you think?
WCF: In my opinion this is a overloaded framework that makes things complicated.
ServiceStack: Seems to be a nice, lightweight, open source alternative. But what if they decided to stop development?
Custom implementation using asp.net mvc such as this, but why reinvent the wheel?

I originally started ServiceStack because of the inefficiency (development and runtime) and friction imposed in creating web services with alternative .NET frameworks.
3-4x Faster Json Serialization than MVC
ServiceStack has a strong focus performance as we believe it provides the best end-user UX which is why it comes in-built with a strong set of Caching providers including the fastest JSON Serializer for .NET - 3-4x times faster than the serializers shipped with .NET and MVC (its default JavaScriptSerializer is the slowest in .NET). For max performance there's no runtime reflection or Regular Expressions used. It employs smart non-linear Route matching and you're recommended to use the much faster built-in Caching providers to work around the poor performance of ASP.NET's Session.
Focused on typed, iterative, code-first development
ServiceStack lets you develop strong-typed web services promoting best practices out-of-the-box using the minimum amount of code and automatically without any code-gen, config, pre/post build-steps, etc.
Example of a simple Hello World service:
public class Hello { public string Name { get; set; } }
public class HelloResponse { public string Result { get; set; } }
public class HelloService : IService
{
public object Get(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
With just these classes, all your web services are automatically made available in a variety of different formats (JSON, XML, JSV, CSV, SOAP) all out-of-the-box with zero effort.
Example of Strong Typed Client API using C#:
var client = new JsonServiceClient("http://localhost/Service");
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
JavaScript example using jQuery:
$.getJSON("http://localhost/Service/hello/World!", function(r) {
console.log(r.Result);
});
Development friendly
Because visualizing web services is important when iteratively developing web services, the default Content-Type when viewing web services in a browser is a human friendly JSON HTML5 Report format (also available stand-alone at http://ajaxstack.com/jsonreport/) which enables you to visualize the response of your web services in a glance.
You also get an automatically generated metadata page (that you can annotate with your own custom description) which serves as a great way to document your web service API.
But what if they decided to stop
development
As the creator of ServiceStack I don't see myself abandoning development in the foreseeable future. I build systems with it daily simply because I find it's a cleaner, faster, more productive framework to develop with.
Promotes best-practices
There are very few .NET web services frameworks that promote a DTO-first message-based architecture enabling the Service Interface pattern - A web services best-practice commonly seen in the Java ecosystem making it easy to develop batch-full coarse grain SOA-based web services.
There is 0 risk it will be abandoned in favour of another .NET web service framework. Simply because we don't believe any other .NET framework actively promotes web services best-practices (i.e. DTO / Remote Façade and Service Interface patterns) and a primary focus on performance.
But even so as an Open Source project with nearly 20 contributors, this fear is mitigated. How many proprietary, closed-source frameworks have MS abandoned and forced everyone to move onto a successor? Open source software evolves, it doesn't get abandoned and rewritten.
The entire source code for ServiceStack lives under http://github.com/ServiceStack there is no lock-in and GitHub makes it easy for anyone to fork and continue development as many have already done.
Works everywhere
Finally, ServiceStack can run on any ASP.NET host in IIS 6/7 on Windows or Linux/OSX using Mono. It also supports a stand-alone HttpListener host allowing you to run it without a web server, i.e. embedded in any Console or Windows application, inside a Windows Service and has even hosted inside a MonoTouch iPhone application.

Been playing with Nancy myself lately and I'm also considering Manos de Mono. Here's the an example from the home page on Nancy.
public class HelloModule : NancyModule
{
public HelloModule()
{
Get["/"] = parameters => "Hello World";
}
}

For me, the easiest and cleanest solution would be to implement the services as controllers in ASP.NET MVC3 with methods that return a JsonResult.
Advantages:
The MVC framework does the heavy lifting for you
You can implement the model validation using attributes instead of code
XCopy deployment to any version of IIS

If I was starting this today I would choose from your third option of doing something Custom in ASP.NET MVC3 or using one of the frameworks below.
WCF Preview 4
Its been re-written by Glenn Block
Here's a sample REST project RestBucks
OpenRasta
Demo application here

Thje Shoulders Of Giants solution is now available via CodePlex and NuGet... renamed as Resources Over MVC.

Related

How to Call Web Service Using SOAP Request with example? [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
Background:
I am creating a webservices site which will provide many types of simple services over SOAP and possibly other protocols too. The goal is to make it easy to do for example conversions, RSS parsing, spam checks and many other types of work. The site will be targeted mostly at beginner developers.
My Problem:
I have never developed any C#, or .NET for that matter. I did hack some VB6 many years ago but that's it. Now I need some examples of doing RPC calls over SOAP in C#. I have tried to search the web, and Stack Overflow, to find this but didn't find many resources, and I have no idea how to rank the resources (which are old? which are incorrect? etc).
I have created a simple example service, which is called like this in PHP:
<?php
$client = new SoapClient('http://webservi.se/year'); //URL to the WSDL
echo $client->getCurrentYear(); //This method returns an integer, called "year"
?>
I now want to call this method as easily as possible in C#. All references and examples are very welcome. Where do I begin? Which classes/modules/whatever can I utilize?
The solution does not have to involve SOAP at all if there are better communication frameworks (the back end is meant to be extensible), but note that the server side is implemented in PHP on Unix so proprietary solutions from Microsoft are out of the question on the server side.
Note that I need this so I can write documentation possible for J. Random Web Developer to follow (even if they are on shared web hosting). I therefore think the best approach should be to do this in code only, but even other ways of doing this are of course welcome.
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
Adding a service reference step by step
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
Open your project (or create a new one) in visual studio
Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.
That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):
Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.
</rant> :)
If you can get it to run in a browser then something as simple as this would work
var webRequest = WebRequest.Create(#"http://webservi.se/year/getCurrentYear");
using (var response = webRequest.GetResponse())
{
using (var rd = new StreamReader(response.GetResponseStream()))
{
var soapResult = rd.ReadToEnd();
}
}
Take a look at "using WCF Services with PHP". It explains the basics of what you need.
As a theory summary:
WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.
The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.
You have the first part of the article here, explaining how to create a very basic WCF Service.
More resources:
Using WCF with PHP5.
Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.
You're looking in the wrong place. You should look up Windows Communication Framework.
WCF is used both on the client and on the server.
Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.
Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.
There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.
Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

How to successfully self-host a ASP.NET MVC app or OData service for a workstation app?

Is it possible to self-host an ASP.NET MVC application and/or OData service in a stand-alone workstation app? Are there any successful examples of doing this?
I would like to create a suite of data-centric applications using .NET that are targeted to EITHER a solo/home user OR a team. Unfortunately, I am the only developer. Comparing front-end technologies of WinForms, WPF, and ASP.NET MVC, I am most proficient with ASP.NET MVC. I would also not like to write multiple implementations of my data service.
(Commenting in lieu of voting down as my profile cannot yet vote down.)
You really need to do some research here. Almost any service-oriented .NET technology can be self-hosted... WCF web services, OData, etc. Your bigger concern should be performance. The more layers you add to your app, and the more times you transform or "serve" your data, the more cycles will be spent processing your data. What you may find is that you users become less happy with the performance compared to a snappy compiled UI hitting a simple business or data layer.
In short, yes, this is possible. However, I would save this type of app for one-off / in-a-pinch apps with either a short life expectancy or very minimal client usage (settings panel, etc.).

Using ASP.NET MVC as Web Service

Does anyone have experience using ASP.NET MVC project as a Web Service?
i.e. using ASP.NET MVC without Views, so other applications can use the URL to GET or POST to the actions in the Controller.
Has anyone used it? If so, are there any drawbacks for not using Web Service project instead?
Thank you all in advance!
It really depends on the kind of application you're writing. I would actually argue the inverse of LukLed's position - SOAP-based services are better suited for internal clients when you want to support things like Windows Authentication, or different protocols like TCP or MSMQ.
Using a more web-style of GETs and POSTs around specific "resources" starts to get you into the REST architectural style. This technique has a few distinct advantages to me:
The response is usually smaller, particularly when using lightweight formats like JSON
Because of the simplicity of the requests and responses, this makes it much easier to use in mobile / native applications (see Twitter's API, for example)
The service you create can be self-describing and discoverable, because you can link to other parts of your API just like normal web pages.
One article that particularly helped me understand the tradeoffs here is Martin Fowler's "Steps Toward the Glory of REST." That being said, it may or may not be the right fit for your application.
If you do choose to build a more REST-based service, definitely consider using the ASP.NET Web API built into MVC4 as others have mentioned. It's currently in beta, but Microsoft felt good enough about it to give it a go-live license.
UPDATE:
Since ASP.NET core, ASP.NET web API has been integrated into MVC 6 project.
https://wildermuth.com/2016/05/10/Writing-API-Controllers-in-ASP-NET-MVC-6
If you want to use simple GET and POST calls, MVC will be good choice. ASP.NET MVC 4 will have support for creating HTTP based APIs. You can read about it here: http://www.asp.net/web-api
Web Service created in Web Service project can be easier to consume, because it can generate WSDL file, that can be easily read and used in many different languages (by using SOAP protocol). On the other side, WS can create huge XML responses, that could be many times smaller, if you used your own format.
If you want to spread your web service around the world, allowing SOAP will make life easier for many developers. SOAP can be used by people, who almost have no idea about programming. If you'll use it internally, prefer speed and simple requests and responses, you can use MVC.
New ASP.NET MVC includes Web Api Kit, which can do exactly what you want. With current version you can still use it. There are no real drawbacks to it

iOS development using C# APIs

I am looking to get into doing some iOS development for a nice addition to a project i am running.
The main project is currently written in C# and is mainly asp.net with a few windows services.
I would like to incorporate this to be able to develop a basic iPhone app as a proof of concept.
From what i have read and understand, its generally best practice to use JSON as a communication medium for iOS.
I am thinking about using WCF to create the API methods so the iOS app can connect to these services to get the data.
Are there any nice tutorials to do this?
Take a look at:
Developing RESTful iOS Apps with RestKit
I do this all the time. WCF Data Services (OData) are the way to go. With OData services, you can specify that you want JSON response by passing (Accept - Application/JSON) in the HTTP Header and OData will return JSON to you.
I have used several libraries for getting OData (which are REST services) from iOS. Microsoft's iOS OData implementation is pretty lame. RESTKit does a really good job for what it handles, but is really painful if you have to do something that it doesn't. I have also used ASI - it is much more flexible than RESTKit, but is not without problems. I ended up writing my own and it suits me just fine.
For a beginner, I would recommend using ASI over RESTKit. RESTKit, while doing a lot of the heavy lifting for you, takes a bit to get working right.
There are two things that are not standard when receiving JSON responses from OData.
1. All responses are captured in a JSONDictionary with the key of "D".
2. Dates are serialized to the JSON standard (number of seconds since 1970), but they are placed in a string like so: /Date(1212353), so you will have to parse out the Date() part of the string before you can use it.
RESTKit doesn't handle either one of these issues natively, so you will have to deal with them if you choose that route. Personally, I would go the ASI route until you learn enough to write your own.
I am considering open sourcing my solution - if I do, I will update this response with the link to it.
---UPDATE----
Just to be clear - if your server side system uses WCF Data Services, otherwise known as OData, then with minor tweaking, RESTKit plays nice with it. If your services are traditional WCF Services (i.e. SOAP Binding), then you will not be able to get JSON out of them because they are bound to the SOAP protocol (Unless you create a custom Behavior to translate it - which I wouldn't do). It all depends on what your services do in essence. If your services are typically data exposure/manipulation (i.e. addCustomer), then you should expose them as OData. If they are truly operations, then you should maybe consider exposing them as actions from a MVC site. Either of them can get you REST services using your existing infrastructure and platform.
If you're using Objective-C to develop the iPhone app, I'm not sure WCF is the best web service technology to use on the server. Check out ServiceStack to create a RESTful service.
Refer following link:
http://www.kotancode.com/2011/04/26/backing-your-ios-app-with-wcf-json-web-services/
It has included comprehensive code samples as well.

REST from asp.net 2.0

I just built a asp.net 2.0 web site. Now I need add REST web service so I can communicate with another web application. I've worked with 2 SOAP web service project before, but have no experise with REST at all. I guess only a coupleweeks would works fine. after googling, I found it's not that easy.
This is what I found:
There is NO REST out of box of asp.net.
WCF REST Starter Kit Codeplex Preview 2 base on .net 3.5 and still in beta
Rest ASP.NET Example
REST Web Services in ASP.NET 2.0 (C#)
Exyus
Handling POST and PUT methods with Lullaby
ADO.NET Data Service
...
Now my question,
a) Is a REST solution for .net 2.0? if yes, which one is best solution?
b) if I have to, how hard to migrate my asp.net from 2.0 to 3.5? is it as simple as just compile, or I have to change a lot code?
c) WCF REST Starter Kit is good enough to use in production?
d) Do I have to learn WCF first, then WCF REST Starter Kit? where is the best place to start?
I appreciate any help here.
Thanks
Wes
If your looking for a project that templates a REST service, you're correct in saying there is no out of the box solution. However, RESTful web services are possible using WCF. The key part is to use several attributes when defining your service functions that let the .NET framework know that the function is not expecting SOAP. The main attribute to use is the WebInvoke attribute.
Here is an example from developer.com:
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/admin/post/{id}")]
void UpdatePost(string id, Post post);
The above code will actually be defined in an interface for your web service. The interface is created automatically when you create your WCF web service project. The actual code for the function will be placed in the class used to implement the web service.
Check out the article on developer.com for a full tutorial. It might seem overwhelming at first if your new to WCF, but after you dive into it, I'm sure you'll start to pick things up quickly. Here is the link for the artile: http://www.developer.com/net/article.php/10916_3695436_1
To answer all of your questions,
a) In .NET 2.0 you should be able to build RESTful services using WSE2.0, but if you have the option to use .NET 3.5, I would strongly recommend going the route of WCF since it is much easier and is designed with REST in mind.
b) Converting your project won't be hard at all. It's just a matter of targetting the new version of the framework in your project settings. Converting a web service from a WSE2.0 service to a WCF service will be a bit trickier though. The easiest way to do so would be to copy the code from each of the different web service functions into the class where you implement the new version of the function. Copy-Paste shinanigans :)
c) I'm not sure what this starter kit is that you're referring to. RESTful web services should be fully supported in WCF which was fully released as of 3.5
d) It would be helpful to understand WCF at least a little before beginning, but it's not crutial to understand it completely in order to get started. I would recommend just reading through the MSDN article on WCF at least once, and then begin working. I'm sure you will come across other questions as you begin, but you can look up those parts as you come across them.
Anyway, I hope this information helps. Good luck to you.
Edit
Some improvements have been made in the REST world. As Darrel Miller mentioned in the comments, WCF was not in fact built with REST in mind. I mis-spoke previously. In fact the framework is built with SOAP in mind and the WebInvoke attribute fills the gap. Although there is a lot of debate around the topic (Web API vs WCF REST), ASP.NET Web API is a new option for building REST services in .NET. I would strongly recommend that anyone who reads this post and is able to use .NET 4.5 in their project look into it as an option.
If you want a framework built with REST in mind, you should have a look at OpenRasta...
http://openrasta.org/
You could look at using ASP.NET MVC as a RESTful web services platform. WCF is probably the way to go in the long run, but MVC should easily handle it. Your actions would just need to be set up to return JSON or XML, depending on how you want to serialize it. MVC offers both a JsonResult and fully customizable ContentResult -- i.e., you serialize your response to a string property on the result and set it's type and encoding.
NOTE: MVC does require 3.5 SP1 so it's not going to be a 2.0 solution. If you require 2.0, you'll need to look elsewhere.
Use WCF REST.
You can use it today. The WCF REST library is ready to go, usable in production.
The WCF Starter Kit (see http://msdn.microsoft.com/en-us/netframework/cc950529.aspx) is something else. It delivers extra stuff; it includes a set of VS project templates, docs, samples and a few tools for building REST apps (client or server) with WCF. One cool tool is the "Paste Xml as Type" command add-in to Visual Studio.
On the other hand, building a REST client, in the general case, I'd recommend taking advantage of the HttpClient assembly in the starter kit (Microsoft.Http.dll). It's small, simple, and useful. A low-risk and high-value dependency even at the current "preview" status of the Starter Kit.
If you were consuming just a single REST service, then you don't need the general Microsoft.Http.dll assembly; you can do all the stuff it does in some code that uses WebRequest. But if you wanted a more general flexible class for manipulating client-side REST requests, then grab that Microsoft.Http.dll.
I'm not sure about a REST solution for 2.0. So I think WCF is going to be the way you'll have to go with this one. MSDN has a long introduction to it.
My personal philosophy is that if a technology is still in beta then I would rather not use it for something that will potentially be a production application so I would start with WCF since it was introduced in the 3.0 version of the framework.
3.0 and 3.5 is actually an update to the libraries, but the CLR is still 2.0 so if the libraries you're using are not deprecated or changed in the new frameworks it should be okay.
Take a look at this CodeProject for a starting point. It seems somewhat... hacky. Modernizing to WCF would be cleaner.
REST, or RESTFUL
Adding this to the System.Web in web.config will enable http get, and put.. aka REST-Like... but not full rest.
<System.Web>
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
</System.Web>

Categories

Resources