I'm having difficulty consuming a WCF REST service, which returns JSON, in a C# ASP.NET MVC application. I'm trying to consume the service in a Controller. I have a ASP.NET MVC project and a service project in the same solution. I've created an entry in my local IIS which points to the service project (i.e. http://localhost/SampleService/).The WCF Service works because I can access the URL and the correct JSON is returned.
Does anyone have any code samples on consuming the JSON via a Controller from a RESTful WCF Service?
You can use the DataContractJsonSerializer:
Here's an example:
var client = new WebClient();
var data = client.DownloadData("http://localhost/SampleService/GetJsonMessage");
var stream = new MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(string));
var result = obj.ReadObject(stream).ToString();
In your controller you can do this to view the result
return Content(result.ToString())
I used WebChannelFactory and it worked great.
You can either use the built-in DataContractJsonSerializer, or the JSON.NET library's JsonSerializer.
I prefer the latter, because it is more robust. Sometimes the DataContractJsonSerializer cannot deserialize a JSON object.
Sample code:
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonText);
To download the library, go to http://json.codeplex.com/
Related
I'm trying to consume the Swagger sample Petstore definition .json file at -
https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v2.0/json/petstore.json
I used VS 2017 > Add > Add REST Api Client functionality. The import is successful and the Swagger Petstore proxy classes are successfully generated and added to my project.
Now I want to write C# code that is actually able to call the Petstore API.I'm unable to find any concrete examples that leverage the proxy classes above.
The way I have worked with REST services has been using the Web Client class in C# -
string sendText = "abc";
WebClient client = new WebClient();
c.Headers[HttpRequestHeader.ContentType] = "text/xml";
result = c.UploadString(url, sendText);
How do I write code that calls the PUT GET POST etc. operation on the Pet Store API?
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);
}
}
I have Skype web API which can be called and used inside javascript.
Now, I have created a simple C#.Net console application and want to use the API.
So, Does c# has any API using which we can run javascript and get the output in json or xml or any other standard format.
Thanks in advance.
You don't need to run Javascript inside your C# code. .NET has its own set of functionality to get the information.
The System.Net.WebClient class has a .DownloadString() method that you can use to get the same information from the Skype API as you would in your JavaScript code.
Take that string that you receive from there and use Newtonsoft's JSON DLL (available through NuGet) to turn that string into a JSON object that you can get all of the information from.
Here is an example of the code that I used to do this in one of my projects, modified for generality. For reference, the DLL's you'll need to add usings for are System.Net, and Newtonsoft.Json.Linq.
private static GetData(string urlParameter) {
string response = string.Empty; // This will be the data that is returned.
string url = "http://skype.api.com/someCall?param={0}"; // The API URL you want to call.
using (var client = new WebClient()) {
// This will get the data from your API call.
response = client.DownloadString(string.Format(url, urlParameter));
}
JObject obj = null; // This is the Newtonsoft object.
try {
obj = JObject.Parse(response);
// Continue on processing the data as need be.
}
catch {
// Always be prepared for exceptions
}
The API you are attempting to call is used by the client through their web browser. It makes no sense to attempt to integrate with it using C# on the server side; it'll never work because it won't be able to talk to Skype running on the user's computer. If you're writing a web app in C# then you need to make the Skype API calls in client-side JS running in the user's browser. If you're not writing a web app then I have no idea what you're trying to accomplish, but it's not going to work.
I wrote a web-service. I wrote a website. I want the website BLL code to call the web-service.
I have a config table with this service URL. I inject the web-service URL to the calling code. What web client or socket in C# should I use that can receive a dynamic web-service URL?
I thought to use:
WebClient webClient = new WebClient();
UTF8Encoding response = new UTF8Encoding();
string originalStr = response.GetString(webClient.DownloadData(BLLConfig.Current);
But maybe there is more elegant way?
I'm loading the configs at run time from a DB table.
Here is how I tried to use a web-reference in Visual Studio:
using (var client = new GetTemplateParamSoapClient("GetTemplateParamSoap"))
{
TemplateParamsKeyValue[] responsArray = client.GetTemplatesParamsPerId(CtId, tempalteIds.ToArray());
foreach (var pair in responsArray)
{
string value = FetchTemplateValue(pair.Key, pair.Value);
TemplateComponentsData.Add(pair.Key, value);
}
}
You can add the URL of the web service as a Web Reference in Visual Studio and then set the Service.URL property to the value from the config
.NET has lots of built-in support for consuming web services... after adding the service reference to your project it generates the necessary code... whcih you can use as is - if you need to configure the URL the generated client class has a URL property which you can set accordingly... for an excellent walkthrough see http://johnwsaunders3.wordpress.com/2009/05/17/how-to-consume-a-web-service/ and see SOAP xml client - using Visual Studio 2010 c# - how?
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.