SOAP to REST Conversion - c#

I have a web service written in C# using SOAP. A client has requested the same service be available as a REST based service.
Is there a clever/quick way I can achieve this, or am I looking at a rebuild from new?

SOAP based services are built with a completely different set of constraints than REST services. If the services is simple then the end result of the two approaches may look somewhat related, but in reality they are two completely different approaches.

SOAP and REST are different not only conceptually but mechanically.
Conceptually SOAP methods are pretty much RPC, remote procedures. So your web methods look like "GetListOfCustomers" and "DeleteCustomer". While in REST you model Customers as resources and use HTTP verbs on these resource. To get the list of customers client will send HTTP GET and server will return customer representation in XML, JSON, HTML or custom format. Customer representation may have embedded URL links that will allow client code to delete customer for example. This is called HATEOAS
Mechanically SOAP is a layer on top of HTTP. Layer that ignores and reimplements existing HTTP capabilities like envelop, verbs, caching, encoding etc. As opposed to REST that relies on all these HTTP features. So mechanically REST is simpler because there is no additional layer that SOAP has.
When you were asked to make existing SOAP service to be available as REST it probably implied purely mechanical aspects. You probably need "XML RPC over HTTP" which will require some work on your part but may not be as hard as redesigning API from SOAP/RPC to REST/HATEOAS.

The solution will depend on how you implemented the SOAP web service.
This is not a "conversion". You will be writing a REST-based service to do the same sorts of thing that your SOAP service does. If you developed your SOAP service correctly, then you will be able to reuse much of the code. You will then be able to deploy a single service that serves both requirements.

Related

ASP.Net Web API vs WCF, which one should I choose in my project

I have read many articles in the web so far, about the differences between WCF and ASP.Net web API. Unfortunately I could not come up to a clear idea about what will serve my purpose. Most of the Articles I have read highlighted on the design point of view of the two web services. But I am confused what will work best for my project and why? Here is my brief description of the project.
I need to create a communication channel between two servers (both are written in C#). The servers will communicate using messages (certain type of commands). The messages sometimes can be only acknowledgements, and sometimes the messages may contain instructions to do some computation. For example, one message can be draw something, or send an SMS etc. And not necessarily the messages will involve any database transactions. But the messages can sometimes send large text files as payload (around 1-5 MB maxm). What I believe WCF is very will surely do this, but can I do the same with ASP.net web API. Because so far all the example I have seen for ASP.Net web api: they are good for RESTful services that manipulate some kind of DB store (GET, PUT, DELETE). But in my case I will need to expose service points that will
do some kind of processing such as return the value of a computation, sending and acknowledging messages, etc.
Not just manipulating a DB-store.
So, what should be the best and simplest way to do so? It is needed to be mentioned that I did not find any straight forward example of achieving this using ASP.Net web API.
The Question you have asked is an overly-broad or primarily opinion-based, and its hard to give an example for what you have asked.
Important Points:
Firstly, if you are going to create a service which would be used on different platforms, then go with WCF.
Secondly, if you are creating internet service which is going to use external resource, then go with Web API.
Web API is the best choice if you are going to create a service for low bandwidth devices or mobile devices to access client.HTTP
request/response is also more readable as compared to SOAP because it
contains header, body, etc. which makes it complex.
Just take few minutes and read the below article, until you get complete understanding of few principles.
Original Source Can be found Here, Here and Here.
To whom choose between WCF or WEB API :
Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.
Why to choose Web API
Web API doesn't have tedious and extensive configuration like WCF REST service.
It is very simple, creating service with Web API. Where as With WCF REST, service creation is bit difficult (requires clear understanding of configurations).
Web API is only based on HTTP and HTTPS and easy to define, expose and consume in a REST-full way.
Web API is light weight architecture and good for devices which have limited bandwidth like smart phones.
My Opinion:
Simplest way to do so - Web API (Since you dont have any examples for this)
Hardest Way is (Configurations) - WCF (Better go with WCF, since you have examples)
I hope this gives you a clear idea about what to choose...
First things first, RESTful is a stateless and uniform interface norm that can be applied to web services. It doesn't have to be automatically and only plain old CRUD service backed by a DB.
In the real world, we can hardly say that all web REST API respect fully the norm, in fact they don't most of the time, especially the stateless part.
For your message based API, especially if it's bidirectional and event based, you can use websockets and consider the REST API a way to expose an uniform, stateless web interface to create those. And yes you can use websockets with ASP.NET WebApi there's plenty of tutorial out there, even for the newer ASP.NET Core.
The "between services" interactions part is no different than the usual Web browser <=> Web service, you're just using C# code instead of JS for the client.
I can hardly recommend WCF that uses SOAP since it's hardly portable considering the web standards nowadays. For instance if want to use a browser client instead of another ASP.NET service, well you'll have to do additional code client side to handle supports.
You can use WCF websockets, providing the almost all the advantages of WCF SOAP.
tl;dr :
You can mix RESTful and Websockets, it can actually be better than going full REST or full Websockets
It's personal preference to use SOAP over websockets but do comes with a potential technical debt considering what you want to do afterwards
Message API between services is no different than a message API between a service and a browser
WebAPI is not just good for RESTful webservices. You can easily send requests to a WebAPI controller and handle it the way you want : calculations, sending messages, interact with a CRM, interact with DB or anything else.
WCF was created to manage SOAP based webservices and brings extra complexity. It handles TCP, Mime...
If you just need to handle HTTP requests, the simplest way is to go with WebAPI.
I would suggest Web API if it is for RESTful services as WCF was never made to serve as Restful services although you can serve as one where as Web API was made particularly for this.

ASP.NET WebAPI + Soap

Does WebAPI support SOAP? I'm trying to write a SOAP Server in MVC4 and whilst I can do it in WCF it seems that WebAPI is replacing this but I see no ways to utilize SOAP in this yet, just JSON / XML using a REST Style interface.
To quote Scott Guthrie: The last few years have seen the rise of Web APIs - services exposed over plain HTTP rather than through a more formal service contract (like SOAP or WS*).
So I would say no.
You should consider looking at ServiceStack which allows your same service to support REST + SOAP APIs, although since SOAP only works over HTTP POST it has some restrictions
Add ServiceStack Reference
As an alternative to SOAP, ServiceStack offers a better alternative to WCF's Add Service Reference which can generate a typed API from a URL using Add ServiceStack Reference feature that's built into ServiceStackVS.
Advantages over WCF
Simple Uses a small T4 template to save generated POCO Types. Updating as easy as re-running T4 template
Versatile Clean DTOs works in all JSON, XML, JSV, MsgPack and ProtoBuf generic service clients
Reusable Generated DTO's are not coupled to any endpoint or format. Defaults are both partial and virtual for maximum re-use
Resilient Messaging-based services offer a number of advantages over RPC Services
Flexible DTO generation is customizable, Server and Clients can override built-in defaults
Integrated Rich Service metadata annotated on DTO's, Internal Services are excluded when accessed externally
WebAPI and WCF both promote RPC method signatures
What's interesting is that despite WebAPI ApiController methods having taken the same RPC approach as WCF in using C# RPC methods to create and define chatty web services with, that they're still not able to support their own SOAP standard made by the same company.
ServiceStack supports REST, SOAP, HTML and MQ endpoints with same service
This is a testament to ServiceStack's message-based design which offers numerous advantages not withstanding being able for the same service to support multiple endpoints and formats including REST, SOAP and MQ endpoints as well as generating server-side or client-side HTML websites if you need it. Here's an example of a rich Northwind database editor that because it was built with ServiceStack automatically enables a typed REST APIs that is able to be called with rich native Desktop clients, Mobile Apps and Single Page Apps.
SOAP is still a poor option for remote services
Although despite supporting SOAP for interoperability, accessibility and backwards compatibility reasons, we don't recommend it for building web services platforms with as it's un-necessarily complex, brittle, slow and verbose and there are much better alternatives to use. I explain more in detail in my interview on InfoQ.
WEB API is Microsoft's answer to REST based apis. If you want SOAP, go with WCF.
WebApi does not support SOAP out of the box, indeed. But it is a quite flexible framework and you could "adapt" it to handle SOAP: nothing prevents you from manually parsing the received SOAP messages (they are plain XML after all) and manually generating the responses as XML strings, then sending them with the approproate content-type header (you could even write your own content formatter for this).
Depending on your needs and your existing codebase, this may be worth the effort or you may want to use a more SOAP-firendly technology such as WCF or the already mentioned ServiceStack framework.
You might want to look at ServiceStack which should support both SOAP and REST in one interface without any hassle. It claims to be a better match than WebAPI for web services.
I can't claim to know everything about the difference, but the problems they claim are inherent in the Web API approach I can say from experience are real - API evolution (inevitable in a real project) is quite tricky in web api. And of course, web api doesn't support SOAP.
It is not like Wed API supports SOAP but due to SOAP is just a standard that uses XML and it travels throw HTTP you can use Web API to expose a POST Service to read the XML and find the nodes you need using XPath and then Deserialize the nodes to objects.
First, you need to add XML support to the ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddXmlSerializerFormatters();
}
Then in your controller, you just need to add a method that receives an XMLDocument and with XPath search for the node you are interested (Basically removing the soap envelope, the header, the body) and then you can deserialize the object.
In my case, I add the service reference using the WSDL and with that, I deserialize the object.
[HttpPost("reservationxml")]
public void CreateReservationFromTSW(XmlDocument soapCreateReservationRq)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(soapCreateReservationRq.NameTable);
nsmgr.AddNamespace("r", "http://soa.company.com/ReservationEnt");
nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
XmlNodeList xmlNodeList = soapCreateReservationRq.SelectNodes("s:Envelope/s:Body/r:CreateReservationRq",nsmgr);
XmlNode xmlnode = xmlNodeList[0];
XmlSerializer serial = new XmlSerializer(typeof(ServiceReference1.CreateReservationRqType));
ServiceReference1.CreateReservationRqType rq = (ServiceReference1.CreateReservationRqType)serial.Deserialize(new XmlNodeReader(xmlnode));
}
As you can see in the next image the service that tries to consume your service uses a Request Method POST with the Accept-Encoding: gzip. That is why you can expose a Web API that can be consumed for a SOAP service.

Current (.NET 4) way to send an XML request to a web service?

What is the most current (.NET 4) way to send a raw XML request to a web service? Does it differ between asmx and wcf services?
I want to build XML via a front-end interface and have the ability to send it to different endpoints. These endpoints could be asmx or wcf. What is the best approach to get started doing this?
I think we mean the same thing; I usually prefer not just to send XML but to work with objects and let the WCF engine to decide in what format itll pass it to the service/client (which might depend on the protocls you and your service providers support). In the terms of WCF, it means defining classes as Data Contracts, and working with their instances only, and not the XML they might represent.
If the other side supports ASMX only, it limits the supported protocols WCF can use to work against to WS-I Basic Profile 1.1 (if Im not mistaken with this), but whatever technology You choose/work against, the concept, in my opinion, should remain the same: in .NET work with classes, and let the underlying communication technology to decide how to serialize and pass it to the other side. Of course, its also more secure than just to send raw string as xml (though you can probably solve some of the security issues by validating against a schema the received xml)

WCF vs ASP.NET Web API [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've spent a few months trying to grasp the concepts behind WCF and recently I've developed my first WCF service application.
I've struggled quite a bit to understand all the settings in the config file.
I am not convinced about the environment but it seems that you can do amazing stuff with it.
The other day I've found out that Microsoft has come out with a new thing called ASP.NET Web API.
For what I can read it's a RESTful framework, very easy to use and implement.
Now, I am trying to figure out what are the main differences between the 2 frameworks and if I should try and convert my old WCF service application with the new API.
Could someone, please, help me to understand the differences and usage of each?
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
If you need to send data on protocols like TCP, MSMQ or MIME
If the consuming client just knows how to consume SOAP messages
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
Since using both till now, I have found many differences between WCF and Web API. Both technology stacks are suited well to different scenarios, so it is not possible to say which is better, this depends on configuration and scenario.
Properties ASP.Net Web API WCF
--------------------------------------------------------------------------------------------------
End point (mainly) Http based SOAP based
Service Type Front End Back-end
Support caching, compression, versioning No
Framework ASP.net WCF
Orientation Resource Oriented Service Oriented
Transports http http, tcp, MSMQ, Named pipe
Message pattern Request reply request Reply, one way, duplex
Configuration overhead Less Much
Security lesser than WCF (web standard security) Very high (WS-I standard)
Hosting IIS IIS, Windows Service, Self hosting
Performance Fast A bit slower than Web API
In use from .NET 4.0 .NET 3.5
Note: The data is not only my view, it is also collected from other official websites.
WCF will give you so much of out the box, it's not even comparable to anything. Unless you want to do on your own implementation of (to name a few) authentication, authorization, encryption, queuing, throttling, reliable messaging, logging, sessions and so on. WCF is not [only] web services; WCF is a development platform for SOA.
Why I'm answering:
I took huge amount of time to understand the difference between these two technologies. I'll put all those points here that I think "If I had these points at the time when I was wondering around in search of this answer, then I have decided very earlier in selecting my required technology."
Source of Information:
Microsoft® Visual Studio® 2015 Unleashed
ISBN-13: 978-0-672-33736-9 ISBN-10: 0-672-33736-3
Why ASP.NET Web API and WCF:
Before comparing the technologies of ASP.NET Web API and WCF, it is important to understand there are actually two styles/standards for creating web services: REST (Representational State Transfer) and SOAP/WSDL. The SOAP/WSDL was the original standard on which web services were built. However, it was difficult to use and had bulky message formats (like XML) that degraded performance. REST-based services quickly became the alternative. They are easier to write because they leverage the basic constructs of HTTP (GET, POST, PUT, DELETE) and typically use smaller message formats (like JSON). As a result, REST-based HTTP services are now the standard for writing services that strictly target the Web.
Let's define purpose of ASP.NET Web API
ASP.NET Web API is Microsoft’s technology for developing REST-based HTTP web services. (It long ago replaced Microsoft’s ASMX, which was based on SOAP/WSDL.) The Web API makes it easy to write robust services based on HTTP protocols that all browsers and native devices understand. This enables you to create services to support your application and call them from other web applications, tablets, mobile phones, PCs, and gaming consoles. The majority of applications written today to leverage the ever present Web connection use HTTP services in some way.
Let's now define purpose of WCF:
Communicating across the Internet is not always the most efficient means. For example, if both the client and the service exist on the same technology (or even the same machine), they can often negotiate a more efficient means to communicate (such as TCP/IP). Service developers found themselves making the same choices they were trying to avoid. They now would have to choose between creating efficient internal services and being able to have the broad access found over the Internet. And, if they had to support both, they might have to create multiple versions of their service or at least separate proxies for accessing their service. This is the problem Microsoft solved with WCF.
With WCF, you can create your service without concern for boundaries. You can then let WCF worry about running your service in the most efficient way, depending on the calling client. To manage this task, WCF uses the concept of endpoints. Your service might have multiple endpoints (configured at design time or after deployment). Each endpoint indicates how the service might support a calling client: over the Web, via remoting, through Microsoft Message Queuing (MSMQ), and more. WCF enables you to focus on creating your service functionality. It worries about how to most efficiently speak with calling clients. In this way, a single WCF service can efficiently support many different client types.
Example of WCF:
Consider the example:
The customer data is shared among the applications. Each application might be written on a different platform, and it might exist in a different location. You can extract the customer interface into a WCF service that provides common access to shared customer data. This centralizes the data, reduces duplication, eliminates synchronization, and simplifies management. In addition, by using WCF, you can configure the service endpoints to work in the way that makes sense to the calling client. Figure shows the example from before with centralized access of customer data in a WCF service.
Conclusion:
i) When to choose Web API:
There is no denying that REST-based HTTP services like those created using ASP.NET Web API have become the standard for building web services. These services offer an easy, straightforward approach for web developers building services. Web developers understand HTTP GET and POST and thus adapt well to these types of services. Therefore, if you are writing services strictly targeted to HTTP, ASP.NET Web API is the logical choice.
ii) When to choose WCF:
The WCF technology is useful when you need to support multiple service endpoints based on different protocols and message formats. Products like Microsoft BizTalk leverage WCF for creating robust services that can be used over the Web as well via different machine-to-machine configurations.If, however, you do need to write an application that communicates over TCP/IP when connected to the local network and works over HTTP when outside the network, WCF is your answer.
Be Warned:
Web developers often view WCF as more difficult and complex to develop against. Therefore, if you do not foresee the need for multiprotocol services, you would likely stick with ASP.NET Web API.
There is a comparison on MSDN about this
WCF and ASP.NET Web API
For me, the choice was about Who the clients are, and where are they located?
Within the company Network and .NET based clients : Use WCF with TCP binding (Fast communication than HTTP)
Outside the company Network, and use diverse technologies like PHP, Python etc: Use Web API with REST
Business speaking, WebApi lacks of a WSDL, so the developers should document all manually. And if, for example, the WebApi operation returns a list of objects then, the client should creates the objects manually, i.e. WebAPI is really prone to errors of definitions.
The pro of Webapi is its more lightweight than WCF.
Regarding the statement "WebApi lacks of WSDL" there are several ways to generate Rest client. One popular approach is Swagger UI / (Swashbukkle Nuget). This gives a rich interface to understand the REST end point's input and output schema and online tool to test the end points.
JSON LD (Json Linked Documents) is another emerging standard which will further improve the JSON based REST developer experience by exposing the JSON schema with better semantics.
With wcf we can configure and expose the same service support for multiple endpoints like tcp, http.if you want your service to be only http based then it will be better to go with web API. Web API has very less configuration when compared to wcf and is bit faster than wcf. Wcf also supports restful services. If you have limitation of .Net framework 3.5 then your option is wcf.

RESTful web services

I am new to RESTful web services. We are taking the REST route for building our public web services to be consumed by out clients.And i had a few questions.
Are there any kind of limitation with pure REST webs services? and if yes then would a hybrid REST web service take care of those limitations?
I am thinking about using SSL + Hash Message Authentication Code (HMAC) in Authorization header for security along with IP based based filtering. what do you guys think about it?
Are there any good client side tools for testing?
Currently i am using the following
http://code.google.com/p/rest-client/
And what about some kind of client side code generation tool?
The following links are my source of info.
http://msdn.microsoft.com/en-us/library/dd203052.aspx
Link
The first thing to keep in mind is that a REST service should be stateless, which is very different when compared to a SOAP/RPC type of service interface. Using REST methodology requires you to rethink how you want your clients to interact with the service, breaking down the interactions into clear and concise method calls.
REST
+ Lightweight messages, very little overhead (other than the XML itself)
+ Easily readable results, can easily test with a web browser
+ Easy to implement
- Looser interface, loose type checking
SOAP
+ More rigid, with a strict contract definition
+ Plenty of development tools available.
Looking through the WCF MSDN documentation, WCF SOAP support was integrated from the start while REST support is a recently added feature. I myself am having a hard time finding documentation for authentication/security for REST services, as most of the documentation is directed towards SOAP.
Client side generation tools: I haven't come across any for REST services as REST doesn't define a service contract as SOAP does. WADL is an attempt to do that for REST services.
http://en.wikipedia.org/wiki/Web_Application_Description_Language
http://wadl.codeplex.com/
I'm interesting in reading more responses dealing with authentication and security, as I'm looking into that myself.
This is a good starting point of a WCF REST WebService:
REST / SOAP endpoints for a WCF service
(BTW: Stackoverflow has nice REST kind of urls.)
You can test a REST service with just a web browser (Go to the url and get the XML or JSON). Fiddler is also good tool, and FireBug-plugin for FireFox. I usually make a thin service-interface project and a separate (unit-tested) logics-project.
For authentication I would first generate a Guid and a timestamp. Then based on those a hash (.NET supports SHA256 and SHA512). The Guid can be stored to server (database table) to map it some concrete numerical id. Then you can have a rest url like:
/myobject/1?timestamp=20100802201000&hash=4DR7HGJPRE54Y
and just disable the hash & timestamp check in development environment (e.g. with AOP). With timestamp I would check that the stamp is between 15 minutes back and forward in time (=should be enough to prevent attacks).
Will your service be visible to the public/internet and is your client a jQuery or Silverlight -client? Then you still have a problem: You don't want to include a secret key in the client software code.
So you need to generate hash in server and some kind of cookie to store the client session. (This can be done e.g. with a separate login-page/application in a folder with different config-file.) I remember that this book did have something on the topic:
If you want to enable the HttpContext when using WCF, you need to set <serviceHostingEnvironment aspNetCompatibilityEnabled="true"> under <system.serviceModel>.
Then you can check current user identity from HttpContext.Current.User.Identity.Name.
However, if you want to make a pure REST service then you don't use cookies, but a HTTP Basic Authentication coupled with SSL/TLS for each call.
I think that it's easy to make a client with just LINQ2Xml or jQuery so maybe client generation is not needed.
Or you can also have both, a SOAP and a REST interface, and use a service reference to make a client.
One thing to keep in mind is that you can take REST as a philosophy (everything should be reachable by a clean URL, without hidden strings attached) or as a dogma (you have to use PUT and DELETE even if that means a lot of hardship down the line).
The emphasis is on simplification - like using simple data types for params instead of stuctured pileups, nor clobering interface for superfluous reasons (like towing giant page "title" in a url), not using headers which are not well known and de-facto standard.
So, you can design perfectly RESTful interface using just GET and retain usability and testability from web browsers. You can also use any standard authentication methods or several of them for redundancy depending on your actual target audience. If you are making an app to run on a corpnet with standardized credentials and tokens you can continue using that. If you are doing something for very general access you can use combination of GET args and/or cookies - keeps your URL-s clean for 99.99% of users.
You can even serve both JSON and XML (like Google maps for example) and still be RESTfull, but you can't do full scale SOAP (complex input types etc). You can do limited SOAP - simple types for requests, always expressible as GET args, people still get WSDL for documentation.
Hope this paints flexible enough picture - the way of thinking above any strict dogma.

Categories

Resources