How to implement SOAP service on WebAPI - c#

We have a server which has several types of api (custom XML API based on httplistener, SOAP API based on WCF and REST API based on WEB API). We want to move all API's to WEB API (there are many reasons) and it should be backward compatible.
One of the reason to support url structure: services/service1. services/service2. And in this case it should be on one port. It is intranet application which is distributed to multiple customers and it should be easy to deploy, install. So, we can not have a long configuration on customer side (proxing and otherts).
Are there easy way for implementation SOAP service on web api? At first look should be easy way to parse httprequest to typed soap envelope (based on existed contract) and serialize a answer. Of course, there many actions and data types in contract.
PS: I do not want to look into servicestack:)
Update:
The problem I described above can be fixed by proxing http request to soap service (It can work only with basichttpbinding without security. If WCF service require NTLM authentication it won't work):
[HttpPost]
public async Task<IHttpActionResult> SoapAction()
{
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8111/soap")
{
Content = this.Request.Content
};
foreach (var header in this.Request.Headers)
{
httpRequestMessage.Headers.Add(header.Key, header.Value);
}
var responseMessage= await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
return ResponseMessage(responseMessage);
}
But I still want to know are there any SOAP parser in C# because my server supports NTLM authentication.

I wouldn't recommend to mix the technologies. Have one project for SOAP Apis and another one for the WebApi, sharing the same logic.
You have then one url for soap, the other one to webapi.
Edit:
I wouldn't do the SOAP Parser at all. That was the power of WCF and would keep on using it.
Since proxing is not an option (Which could be done in web.config and easily deployed), I would create a WebAPI endpoint which would redirect to SOAP API.
[HttpGet]
public IHttpActionResult Service1()
{
return Redirect("http://service.com/soap/services/service1");
}
Later, when migrating the logic, use the service itself.
[HttpGet]
public IHttpActionResult Service1()
{
var result = new ServiceLogin1().Execute();
if(result == null)
{
return StatusCode(HttpStatusCode.NoContent);
}
else
{
return Ok();
}
}

I think this is already answered here ASP.NET WebAPI + Soap
If what you are asking for is how to create REST wrappers that call into the SOAP implementations then library's like ServiceStack do this for you but if you want to do it yourself with WebApi it's pretty easy. Just make a separate project that has your SOAP service references in it wrapped in some sort of abstraction and then reference that in your WebApi project and call into it from your REST endpoints.
If what you are asking is how to host the SOAP interfaces in WebApi I think you are just making more work for yourself. Use the WCF scaffolding that MS has provided. WebApi for REST services, WCF for SOAP.

Related

REST Batch\Bulk API implemetation in WCF similiar to Facebook API

I'm implementing new REST API method which allows calling other REST API methods in batch\bulk manner. Similar to Facebook's https://developers.facebook.com/docs/graph-api/making-multiple-requests
Request example:
POST /batch
[
{"method":"GET", "relative_url":"/user/anton"},
{"method":"GET", "relative_url":"/user/vitaliy"}
{"method":"POST", "relative_url":"/user/dan", "body":{name:Dan}}
]
Response example:
status 200
[
{"status":"200", "body":{name:"Dan"}},
{"status":"404"},
{"status":"201"}
]
In short, batch method should on server-side call OTHER methods one-by-one and return result as array of results.
The most simple solution will be create .Net HttpClient on server side and call other WCF methods on-by-one.
The question is: How implement this using WCF infrastructure without calling WCF method externally via HttpClient?
The reason for that - I don't want to have network-round trips.
The most perfect solution will be to use .Net Reflection, but this not good solution in terms of REST abstraction
The most close solution is create WCF Message including HttpRequestMessageProperty (URL, Headers, Method, Content-Type) and send it to processing by WCF infrastructure (just it was sent via HTTP protocol) (not sure about this):
Message responseMessage = wcfInsfrastucture.Process(createWcfMessage(url, method,contentType,body));
Currently I'm lost in WCF Samples, and WCF server-side channel architecture.
Most similar question was asked in Sending custom WCF Message to a service but I can't making it work with existing configured server-side behaviors.
Similar questions:
Sending custom WCF Message to a service
https://stackoverflow.com/questions/26049136/generic-way-to-send-wcf-messages-to-different-channels
How implement this using WCF infrastructure without calling WCF method externally via HttpClient?
The only way I found is to implement request-response pattern over WCF.
Create a single entry point in WCF service, that receives an abstract request as an argument and returns an abstract response.
For example,
<OperationContract> function Execute(Request as IRequest) as IResponse
Create concrete request and response classes for service operations
Create CompositeRequest and CompositeResponse for Batch / Bulk operations
All service has to do is to apply business logic according to request type.
In case service receives CompositeRequest it just calls the same Execute method for all nested requests one-by-one and aggregates responses into CompositeResponse.

Using Bing API: easiest way to connect with an API and get data from it

I've searched some time, looking for easy way to connect with some other sites WebAPI. There are some solutions, but they are made in very complicated way.
What I want to do:
Connect with server using URL adress
Provide login and password to get some data
Get data as JSON/XML
Save this data in an "easy-to-read" way. I mean: save it to C# variable which could be easy to modify.
Currently, API that I want to work with is Bing Search, but I'm looking for some universal way. I found an example, but it doesn't work for me and in my app I can't use this class: "DataServiceQuery" because it doesn't exsist.
How do you usually do it? Do you have your favourite solutions? Are there some universal ways or it depends on type of API that you work with?
I'm currently working on .NET MVC app (in case it could make any difference)
From server side
You can use that like below.
// Create an HttpClient instance
HttpClient client = new HttpClient();
// Send a request asynchronously continue when complete
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
var result = readTask.Result
//Do something with the result
});
});
You can see example on following link.
https://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
For JavaScirpt:
You could use jQuery and WebAPI both together to do your stuff.
There are few steps to it.
Call web api with Ajax jquery call.
Get reponse in JSON
Write javascript code to manipulate that response and do your stuff.
This is the easiest way.
See following link for reference:
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
It entirely depends on the type of API you want to use. From a .Net point of view, there could be .Net 2 Web Services, WCF Services and Web API Services.
Web APIs today are following the REST standard and RMM. Some APIs need API Keys provided as url parameters, others require you to put in request's header. Even some more robust APIs, use authentication schemes such as OAuth 2. And some companies have devised their own standards and conventions.
So, the short answer is that there is no universal way. The long answer comes from documentation of each API and differs from one to another.

Accept WCF request in WebAPI

I need to enable my webAPI REST service to accept a request in the format of:
www.someURL.com/OldService.svc
I am working on an existing application that used to use WCF. These methods do not have to return anything but a 200 response. We need the REST service to handle this call so we can retire the old WCF service, but systems will fail if we don't support this WCF request.
Has anybody done this before?
edit:
Is it possible to do this with just adding a new route?
You can add a WCF service (.svc) to a Web API project by simply adding a New Item and selecting Web, it will then show up in the list as WCF Service.
Maybe you could use the Route attribute(using System.Web.Http) for the old service? I've used this for route names like [Route("SomeRoute")] but I'm not 100% sure if the .svc extension will interfere with anything.
[Route("OldService.svc")]
[HttpPost]
public HttpResponseMessage NewData(Data SomeData)
{}

Android Rest Asp.net Web Services?

I am new on android, i want to use asp.net webservices in my android app.
but i dont know how i can use this?.
i want to do with Restful method.But when i search in google, i found all tutorials in soap.
Is soap is compulsory for asp.net or there is ant other option available that we can use rest for asp.net in android.
i have follow this tutorials.link
You can always use JSON.
Json is the fastest data transfer mode across network, so your webservice should return data in Json format.
Once you have Json you can always render it and use it as needed.
Here is example to render data
http://www.tutorialspoint.com/android/android_json_parser.htm
You can create a WCF REST web service
http://msdn.microsoft.com/en-us/library/ms731082(v=vs.110).aspx
or an easier way is to create a new MVC4 web application, and update your Controller to extend Api Controller, then create a new web method that will return a HttpResponseMessasge like so:
public class MyController : ApiController
{
public HttpResponseMessage MyWebMethod()
{
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.Write([WRITE YOUR JSON HERE]);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}

wcf json web service

What is the best way to create a JSON web service? We have another team that is using Java and they insist to having all communication done using JSON. I would prefer to use WCF rather than any 3rd party framework.
I found this blog: http://www.west-wind.com/weblog/posts/164419.aspx, and it suggests that the Microsoft implementation is flawed with M$ specific crap.
If you use WCF and the 3.5 Framework, it couldn't be easier. When you mark your OperationContracts with the WebGet attribute, just set the ResponseFormat parameter to WebMessageFormat.Json. When the service is accessed RESTfully, it will return the data using the DataContractJsonSerializer.
It's really helpful to mark the POCOs that you want to JSON serialize as [DataContract] and to mark each serializable member as [DataMember]. Otherwise, you end up with funky JSON, as Rick pointed out in his blog post.
I maintain a mature Open Source alternative to WCF in ServiceStack, a modern, code-first, model-driven, WCF replacement web services framework encouraging code and remote best-practices for creating terse, DRY, high-perfomance, scalable REST web services.
It includes .NET's fastest JSON Serializer and has automatic support JSON, JSONP, CORS headers as well as form-urlencoded/multipart-formdata. The Online Demos are a good start to look at since they all use Ajax.
In addition, there's no XML config, or code-gen and your 'write-once' C# web service provides all JSON, XML, SOAP, JSV, CSV, HTML endpoints enabled out-of-the-box, automatically with hooks to plug in your own Content Types if needed.
It also includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
This is the complete example of all the code needed to create a simple web service, that is automatically without any config, registered and made available on all the web data formats on pre-defined and custom REST-ful routes:
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService<Hello> {
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Above service can be called (without any build-steps/code-gen) in C# with the line below:
var client = new JsonServiceClient(baseUrl);
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Console.WriteLine(response.Result); // => Hello, World
And in jQuery with:
$.getJSON('hello/World!', function(r){
alert(r.Result);
});
What is the best way to create a JSON web service? We have another
team that is using Java and they insist to having all communication
done using JSON. I would prefer to use WCF rather than any 3rd party
framework.
Here's an easy-to-follow walkthrough, which takes you through the process of setting up your first WCF Service, then linking it to a SQL Server database.
http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm
It uses Microsoft's beloved Northwind SQL Server database, and shows how to write a simple JSON WCF Web Service to read and write it's data.
Oh, and it then shows how to consume the JSON data using JavaScript or an iOS application.
Good luck !
I ended up using JayRock. Its fantastic piece of technology, just works. You don't get any NullReferenceExceptions like from this crap WCF if you don't configure it correctly.

Categories