I am really new in JSON, and I am trying to create a web service(.asmx) in c# that will return the JSON object with key and value. I am creating this web service for one of my android app that why its must to return the JSON object with key and its value. Below is my code of web sevice:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Json;
using System.Web.Services;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.IO;
using System.Web.Script.Services;
using System.Collections.Generic;
namespace WebServiceExample
{
/// <summary>
/// Summary description for AddTwoNumbers
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//[System.Web.Script.Services.ScriptService]
public class AddTwoNumbers : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Add(int a, int b)
{
// 1st way to return Key and Value
JsonObject jso = new JsonObject();
JsonValue jv1 = 1;
JsonValue jv2 = 2;
jso.Add("Key-1", jv1.ToString());
jso.Add("BoolValue", jv2.ToString());
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(jso);
return strJSON;
}
}
}
With the above code I am getting the following output:
http://d.pr/i/NWxp
Please click on the above link to see my output.
As you can see I am getting the key but not the value. I am stuck.
Please help. Thanks
EDIT : If I am doing in a wrong way, so please suggest me the right way to add keys and values in JSON object. I searched a lot on google but unable to understand properly.
ANY QUICK HELP PLEASE
UPDATE :
public string GetPeople()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Key-1", "value-1");
dict.Add("Key-2", "value-2");
dict.Add("Key-3", "value-3");
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(dict);
return strJSON;
}
Related
Question is: Did I define the client resource call correctly, or is there something wrong in the server code?
I have a REST API server I am coding in C# / Visual Studio 2019 using the Web API template. I have 2 paths at the moment - a POST and a GET.
POST: /api/account
GET: /api/account/{accountid:long}
POST works great using SoapUI as a test client, but GET gives me a connection reset (message is "Error getting response; java.net.SocketException: Connection reset").
I hope I defined the resource correctly:
Here's my Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using Coda.Core;
using CodaRESTServer.Models;
using System.IO;
using System.Diagnostics;
namespace MyRESTServer.Controllers
{
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
[HttpGet]
[Route("{accountid:long}")]
// GET api/<controller>/5
public JObject Get(long accountid)
{
var x = new JObject();
x["worked"] = "true";
return (x);
}
[HttpPost]
[Route("")]
// POST api/account
public JObject Post()
{
var x = new JObject();
x["worked"] = "true";
return (x);
}
}
}
I specified it wrong in SoapUI. It needs to be:
/api/account/{accountid}
And then I can click on the Parameters field and enter the value.
I am a frontend developer so forgive my lack of ability to explain my issue.
I am trying to create some pages in an Umbraco project that display data using Vue.js. For this, I am trying to set up a custom API controller that will return the data I want, when called.
A simple example would be that I want to return all blog articles. Below is the code I have currently got:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using System.Web.Http;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public string Test()
{
return "qwerty";
}
}
}
I've read numerous articles and just can't seem to grasp what I need to do to query Umbraco for the data I want back?
I've tried adding
var content = Umbraco.TypedContent(1122);
And then returning that but I get errors stating:
(local variable) Umbraco.Core.Models.IPublishedContent content
Cannot implicitly convert type 'Umbraco.Core.Models.IPublishedContent' to 'string'
I have then tried serialising the var content but I get stuck with:
Self referencing loop detected for property 'FooterCtalink' with type
'Umbraco.Web.PublishedContentModels.Blog'. Path
'ContentSet[0].FeaturedProducts[0].Features[0].ContentSet[0]'.
Any help would be fantastic!
EDIT:
I have no edited the controller to be like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Web;
using Umbraco.Web.WebApi;
using Umbraco.Web.PublishedContentModels;
using Newtonsoft.Json;
using System.Web.Mvc;
using DTOs.PostDTO;
namespace Controllers.WebAPI.Qwerty
{
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public PostDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new PostDTO();
// 3. Pupulate your DTO
myDTO.Url = content.Url;
// 4. return it
return myDTO;
}
}
}
And created a DTO like so:
namespace DTOs.PostDTO
{
public class PostDTO
{
public string Url { get; set; }
}
}
However, when console logging my data after the ajax request, I only only getting 1122.
The issue is that you can't return a .NET Object in JSON that has the circular dependency.
To solve your problem, you can simply follow the below steps:
Create your own DTO & add required properties in that.
Fetch content from Umbraco API in C# & populate your custom DTO object.
Return that DTO from JsonResult.
Your code will look like below:
[Route("api/[controller]")]
public class PostsApiController : UmbracoApiController
{
[HttpGet]
public MyDTO Test()
{
// 1. Get content from umbraco
var content = Umbraco.TypedContent(1122);
// 2. Create instance of your own DTO
var myDTO = new MyDTO();
// 3. Pupulate your DTO
myDTO.SomeProperty = content.SomeProperty;
// 4. return it
return myDTO;
}
}
You are on the right track.
I think you need to return ActionResult instead of string.
Something like:
[HttpGet]
public ActionResult Test()
{
var content = Umbraco.TypedContent(1122);
return new JsonResult(content);
}
This should return the umbraco object as Json.
My project is to write a web service and a web form that consumes it. It should have two text boxes and a button. The user enters an text speak acronym in the first text box and presses the button. The web service compares the textbox1 entry against a dictionary file, and displays the resulting full word in the second text box. This is the code I have so far and I am really struggling to get it to work, any help would be appreciated. At this point I have 'Type or namespace definition, or end of file expected' error. Here are the two files i have.
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(File.OpenRead(#"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(';');
_dictionary[tokens[0]] = tokens[1];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
localhost.Service obj = new localhost.Service();
TextBox1.Text = (obj.Translate());
}
}
Service.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string Translate(string input)
{
string output;
if(_dictionary.TryGetValue(input, out output))
return output;
// Obviously you might not want to throw an exception in this basis example,
// you might just go return "ERROR". Up to you, but those requirements are
// beyond the scope of the question! :)
throw new Exception("Sinatra doesn't know this ditty");
}
}
}
Not sure if the question is still unanswered. But here are my suggestions.
In the web service file i.e. say Service1.cs you are not declaring the _dictionary object. So you will be moving the dictionary object declaration and initialization in the constructor of the service.
Some thing like this below.
public WebService1()
{
using (var reader = new StreamReader(File.OpenRead(#"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(',');
_dictionary[tokens[0]] = tokens[1];
}
}
}
Also in the split method I would assume you wanted to use the comma instead of the semicolon(that was used in your sample).
And then in the consumption of the service, you would do some thing like this below. I was not sure what you were trying to do using the localhost object in your sample.
ServiceReference1.WebService1SoapClient obj = new WebService1SoapClient();
TextBox2.Text = obj.Translate(TextBox1.Text);
Hope this helps.
-Davood.
I am currently working to understand SOAP protocol with C#, I find some examples in Google and understand the envelope, header, body.
I authenticate with the webservice but I want to know where can I to implement a class or method to access a database with the user and password provided, I mean, soap header has user="john" pass="odos223kiwi0X" the server received the header, now access to database with the user provided and check the password.
if a right option create a custom method in the soap Class to do it?
you can create a class just as the following :
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.Web.Services;
using System.Net;
[System.Web.Services.WebServiceBindingAttribute(
Name = "FunctionName",
Namespace = "nameSpace")]
public class ClassName:
System.Web.Services.Protocols.SoapHttpClientProtocol
{
public ClassName(string uri) // Constractor
{
this.Url = uri; // the full path for your server we will make later on in the answer
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute(
"nameSpace/ClassName",
RequestNamespace = "nameSpace",
ResponseNamespace = "nameSpace",
Use = System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public object[] FunctionName(string Parameter1)
{
object[] results = { };
try
{
results = this.Invoke("FunctionName", new object[] { Parameter1});
return ((object[])(results[0]));
}
catch (Exception error)
{
object[] webException = { -1, error.Message };
return (webException);
}
}
}
and now we create the asmx service:
create a web service and add this under the namespace :
[WebService(Namespace = "NameSpace")] //same namespace you wrote in the class
then add your function and Object[] as returning value.
[WebMethod]
public object[] FunctionName(string Parameter1) // function name and parameters should be the same in your class where you called the web service (case sensitive)
{
... // your code
}
** you can download http://www.fiddler2.com/fiddler2/version.asp that will allow you to see and trace the out going requests
please send me back if you need any farther info.
I am reading Designing Evolvable Web APIs with ASP.NET. In one of the exercises, the book has me edit a Controller using Visual Studio. This is being done in ASP.NET using C#. The template I used was the standard ASP.NET web application API.
I have edited the controller to the way the book shows (although it does not seem to give very specific directions). Here is what my controller looks like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using WebApplication4.Models;
using WebApplication4.Providers;
using WebApplication4.Results;
namespace WebApplication4.Controllers
{
public class GreetingController : ApiController
{
public string GetGreeting() {
return "Hello World!";
}
}
public static List<Greeting> _greetings = new List<Greeting>();
public HttpResponseMessage PostGreeting(Greeting greeting)
{
_greetings.Add(greeting);
var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
response.Headers.Location = greetingLocation;
return response;
}
}
I get errors on:
_greetings: A namespace cannot directly contain members such as fields or methods
PostGreeting: A namespace cannot directly contain members such as fields or methods,
_greetings : does not exist in the current context
Request : <invalid-global-code> does not contain a definition for 'request',
Created: HttpStatusCodeREsult does not contain a definition for 'Created'
As the error is trying to tell you, your fields and methods must be inside the class.
Check your braces.
Your _greetings field needs to be part of the class, as well as the PostGreeting method, it seems you just closed "}" of the class a bit early.
MOve the "}" before the _greetings field to the end of the file, like:
namespace WebApplication4.Controllers
{
public class GreetingController : ApiController
{
public string GetGreeting() {
return "Hello World!";
}
public static List<Greeting> _greetings = new List<Greeting>();
public HttpResponseMessage PostGreeting(Greeting greeting)
{
_greetings.Add(greeting);
var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
response.Headers.Location = greetingLocation;
return response;
}
}
}