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.
Related
So I was thinking about learning about app development for android. I know you use kotlin however, I also want to start working with .NET and C# is there a possibility for my first app that I create a basic login and register form in the app using Kotlin and connect it to a .NET REST API? Is that a thing I am sure you are just using the URL for the API call?
Sure! Using Retrofit, the Android app could be connected to the RESTful APIs that is available using the latest technology by Microsoft and the open source community; ASP.NET Core Web API 5.
A complete guide to do so:
http://codingsonata.com/a-complete-tutorial-to-connect-android-with-asp-net-core-web-api/
yes it is possible, there are plenty of libraries that are able to help you with that, like Retrofit or Volley
Yes. It's a very common way to consume API for data processing purposes in android-based applications.
If you have learnt on how to consume API with Android Application (built using JAVA), it's pretty much the same.
if you have never used JAVA to create android applications that consume API, don't worry because the process you need to do is very simple, moreover there are already many collections of libraries that you can use for this purpose. You can try to look on several library such as Retrofit and OkHttp.
Let me show you a a simple example of using OkHttp to pass data from android to API. This simple example is quoted from this article
private val client = OkHttpClient()
fun run() {
val formBody = FormBody.Builder()
.add("search", "Jurassic Park") /*The parameters*/
.build()
val request = Request.Builder()
.url("https://en.wikipedia.org/w/index.php") /*API URL*/
.post(formBody)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
I hope this answer can be helpful for you. If you need more assistance, don't hesitate to contact.
If you are using API, you use URL and model of your data.
I recommend Retrofit as a library for connecting to any API. A good example is here, check out this and I think you will be well prepared to write Kotlin code.
Firstly, you need to define retrofit client, with your URL:
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
then you need to map your API as an interface, for example if you have an endpoint https://reqres.in/api/users? you must define them like this:
#GET("/api/users?")
Call<UserList> doGetUserList(#Query("page") String page);
For creating .NET Core API, especially with user registration you must check some of tutorials, I recommend to be familiar with EF Identity (other).
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.
I have recently returned to .net programming after a 7 year break.
I need to learn how to write a project within an existing open source asp.net mvc 5 ecommerce solution to receive posted json strings from a remote server running php with cURL, send acknowledgement responses, create my own json strings to post back to the remote server and receive acknowledgement responses. This must all be done with server side code, with no client side component whatsoever.
Serializing and deserializing json is not the issue, its using the correct kind of pages or services to send and receive json on the server without any client component, and using http objects directly. I have no experience or knowledge of creating this kind of project.
This is my question: I have had a look at a couple of tutorials about using .ashx and httpClient and httpContext but found them a little confusing. I would like to find a comprehensive guide about how to use json to communicate server to server with realistic examples. Is there one available?
Sounds like a perfect use case for WebApi. It is made specifically to work with JSON (or XML) requests and should work fine with requests issued by other scripts (not browsers).
There are plenty of tutorials available. Here is the official introduction tutorial.
What I often do to create JSON in C# is make an object/class which I serialize to JSON.
My controller has an function:
public JsonResult FunctionName()
{
var json = new { x1 = 10, y1 = "Hello" };
return Json(json);
}
You can call that function with PHP.
The ONLY argument I can see for SOAP WCF over REST (json) wcf is the fact that once my service is created I can add a a reference in visual studio and I get a load of strongly typed classes ready for me and a client class that I can call all my webmethod through. It even sets up the web.config as far as I remember.
However when I expose a REST (json) service I still get a WSDL. So Im wondering is there still a way to build my references automatically?
Not using WCF tools. Unlike with SOAP (which has an established protocol for describing services - WSDL), REST doesn't. WADL is one such protocol, but it isn't too widespread and WCF does not support it. You still get a WSDL, because WCF will describe everything it can from the service. However, the WSDL won't have a <wsdl:port> element, which would describe the REST endpoint, which is why you get the WSDL, but cannot generate a reference to it.
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/26/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work.aspx has a lot more info on this issue.
Very old question, newer answer.
today using openapi (swagger) I can achieve this by using swagger inspector doing samples i can document my rest services as well as create a spec yml/json file allowing for validations and acceptance criteria as well as automated clients for java,python,c#,ruby,javascript and others I'm sure
I would like top elaborate:
Although it is true you cannot get a WSDL add service reference with a JSON REST WCF service, what I do is create two met data hooks:
is the operations returning JSON
is a single XML op returning a class wrapper which includes all the service classes I allow, I call it Discover:
i.e.
public class Discover
{
public Manager Manager {get;}
public Employee Emp {get;}
....
}
[OperationContract]
public Discover DiscoverDTOs()
You can, indirectly. While the client generated by Visual Studio won't work, that client implements an interface, also generated, that you can use like this:
WebChannelFactory<IService> factory = new WebChannelFactory<IService>(new Uri(endpointAddress));
IService proxy = factory.CreateChannel();
int result = proxy.Operation(1, 2, 3);
WebChannelFactory has another overload which accepts a WebHttpBinding, you can configure based on the service configuration, or you can make this configuration manually in your app.config file.
I am trying to get data form a web service inside a silverlight app. Unfortunately the silverlight app (Bing map app) just hangs when trying to connect.
I use the same code in a console app and it works just fine.
Is there anything special I need to do in silverlight to get it to work? I don't get any exceptions - it just hangs.
I based my service and client code off of this example
http://www.switchonthecode.com/tutorials/wcf-tutorial-basic-interprocess-communication
Problems and Questions:
1. Why can't I set breakpoints in my sliverlight code?
2. How can I successfully call WCF service from a silverlight app? (links to SIMPLE working examples would be great - all the ones I seem to find seem to be quite advanced (RIA, Duplex, etc) Many of these also show xml and other non C# "code" - frankly I don't know what those do and how they relate to the projects, code and services.
(Clearly I am quite ignorant about WCF and silverlight)
As per request for code:
[ServiceContract]
public interface ILGSMapServer
{
[OperationContract]
List<double> GetLatitudes();
}
public class TreeWorkClient
{
ChannelFactory<ILGSMapServer> httpServer;
public ILGSMapServer httpProxy;
public TreeWorkClient()
{
httpServer = new ChannelFactory<ILGSMapServer>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8000/GetLatitudes"));
httpProxy = httpServer.CreateChannel();
}
public List<TreeWorkItem> GetLocations()
{
List<double> lats = httpProxy.GetLatitudes();
//... do stuff in code
return ret;
}
}
I agree with John Saunders - it would be easier to answer this if you published the client code.
However as a guess, a common problem with calling services from Silverlight applications is the restriction Silverlight puts on cross domain calls.
In summary, if your service is at a different domain from the site-of-origin of the Silverlight application, you need to create a client access policy file at the service location.
See this for details:
http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
Given your example code you should be seeing the
System.InvalidOperationException: The contract 'ILGSMapServer'
contains synchronous operations, which are not supported in
Silverlight. Split the operations into "Begin" and "End" parts and set
the AsyncPattern property on the OperationContractAttribute to 'true'.
Note that you do not have to make the same change on the server.
You'd need to change your service contract to the following
[ServiceContract]
public interface ILGSMapServer {
[OperationContract( AsyncPattern = true )]
IAsyncResult BeginGetLatitudes( AsyncCallback callback, object context );
List<double> EndGetLatitudes( IAsyncResult result );
}
This also means you'll need to do something completely different in your GetLocations() function as this function will return before the results from the Web have been returned.
Try taking a look at the examples here.
Other options involve using the "Add Service Reference" rather than manually defining it in code.
I believe you need to have this attribute on WCF service for SL to consume it:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
As for debugging - you can debug Silverlight, try using IE for that, its most natural browser for SL debugging (sadly).
Once you start debugging it will be more clear whats wrong when you catch cross domain exception or some other.