C# create rest webservice - c#

I created a Rest webservice in visual studio 2010 like this:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DocService
{
[WebInvoke(ResponseFormat = WebMessageFormat.Json,UriTemplate = "", BodyStyle = WebMessageBodyStyle.Wrapped)]
public data GetCollection(Stream streamdata)
{
}
}
User will send request with json data to this service:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
var jsonData = JSON.parse(JSONObject);
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
data: jsonData,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First problem: How can I access that json in my code?
For now I do like this (But json array can't serialize correct):
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
string resDecode = HttpUtility.UrlDecode(res);
NameValueCollection nvc = HttpUtility.ParseQueryString(resDecode);
var json = new JavaScriptSerializer().Serialize(
nvc.AllKeys.ToDictionary(k => k, k => nvc[k])
);
Output:
res = "pCode=123456789&mCode=001&tCode=&dArr%5B0%5D%5BdCode%5D=26&dArr%5B1%5D%5BdCode%5D=27&sId=sk"
resDecode= "pCode=123456789&mCode=001&tCode=&dArr[0][dCode]=26&dArr[1][dCode]=27&sId=sk"
nvc = {pCode=123456789&mCode=001&tCode=&dArr%5b0%5d%5bdCode%5d=26&dArr%5b1%5d%5bdCode%5d=27&sId=sk}
json = "{\"pCode\":\"123456789\",\"mCode\":\"001\",\"tCode\":\"\",\"dArr[0][dCode]\":\"26\",\"dArr[1][dCode]\":\"27\",\"sId\":\"sk\"}"
Second problem: In ajax, after request sent, it's always done with error and xhr.status and thrownError are 0 and null but with Fiddler I can see json output

Answer to the first problem:
Best way to use json in c# is to create a class with properties with exact name and type of the json object and then deserialize that json like this:
RequestClass reqParam = new RequestClass(); //Class with properties same as json object
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
JavaScriptSerializer js = new JavaScriptSerializer();
reqParam = js.Deserialize<RequestClass>(res);
Answer to the second problem:
My final javascript is like this and work fine:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
//Delete parse line
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
contentType: "application/json", //Added
data: JSONObject, // This line changed
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

Related

WebApi 2 - Json request pending

when I call one webapi from ajax, if I return something different from simple string or int, the request is still pending.
here my javascript:
var endPoint = "/api/services/attivita/set";
$.ajax({
url: endPoint,
data: JSON.stringify(
{
'id': attivita.IDTipoAttivita,
'descrizione': $('#Descrizione').val()
}
),
dataType: 'json',
contentType: "application/json;charset=utf-8",
processData: false,
type: 'post',
success: function (data) {
console.log('ok');
},
error: function (data) {
console.log('ko');
}
});
and here webapi code
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/services/attivita/set")]
public TipoAttivita SetAttivita([FromBody] dynamic obj)
{
var id = (int)obj.id;
var descrizione = obj.descrizione.ToString();
var nuovo = id == -1;
var attivita = new TipoAttivita()
//do stuff of attivita object
this.CurrentDb.TipoAttivita.Add(attivita);
this.CurrentDb.SaveChanges();
return (attivita);
}
If I change to "public int...." and "return(1);" at the end of the function everything works fine.
in WebApiConfig.cs I have this
var jsonFormatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
};
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Clear();
config.Formatters.Add(jsonFormatter);
Any idea?
Thanks a lot
Try to change return type to IHttpActionResult and return Ok(attivita)

JSON Invalide primitive

I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}

How to deserialize Json Stream in c#

I have following method and i need to deserialize the retrieve stream.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val= JsonSteamToString(jsonString);
}
public string JsonSteamToString(Stream jsonStream)
{
StreamReader reader = new StreamReader(jsonStream);
return reader.ReadToEnd();
}
My class is as follows:
public class H2JsonStateObject
{
public string url { get; set; }
public string stateId { get; set; }
}
I'm calling this method using Ajax call as follows:
var value ="89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9";
var link="RedirectPage.aspx";
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
var jsonToSend = JSON.stringify(data);
$.ajax({
cache: false,
url: "StateRedirectService.svc/RefreshPagemethod",
type: "POST",
async: false,
data: jsonToSend,
success: function (data, textStatus, jqXHR) {
window.location.href = link;
},
error: function (xhr, status, error) {
alert('error');
}
});
When the request receive to web method and after converting the value it get following string.
"\"{\\\"url\\\":\\\"RedirectPage.aspx\\\",\\\"stateId\\\":\\\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\\\"}\""
Now i need to deserialize url & stateId. How can i do that?
I tried followings. but couldn't able to deserialize.
Using DataContractJsonSerializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(val)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(H2JsonStateObject));
H2JsonStateObject p2 = (H2JsonStateObject)deserializer.ReadObject(ms);
}
It throws exception and says :
Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
Using JavaScriptSerializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Object obj = serializer.DeserializeObject(val);
This gives me my object as string value as follows:
"{\"url\":\"RedirectPage.aspx\",\"stateId\":\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\"}"
What I did wrong and how can i get RedirectPage.aspx and 89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9 value?
Able to solve this problem in following way. my problem is with Json string value.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val = JsonSteamToString(jsonString);
string JsonVal = val.Replace("\"", "'");
var json_serializer = new JavaScriptSerializer();
H2JsonStateObject myobj = json_serializer.Deserialize<H2JsonStateObject>(JsonVal);
H2RequestRedirect.RedirectToTemp(myobj.url, myobj.stateId);
}
in here string needs to be in following format.
JsonVal = "{'url': 'RedirectPage.aspx','stateId': '89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9' }";
When i'm calling this method i send json object without JSON.stringify(data);
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
$.ajax({
cache: false,
url: "StateRedirectService.svc/RedirectHyperlink",
type: "POST",
async: false,
data: data,
success: function (data, textStatus, jqXHR) {
//alert('OK');
window.location.href = link; },
error: function (xhr, status, error) {
alert('error');
}
});
Then it works as a charm...

Javascript and C# Handler - AJAX with JSON, sending array

When I send an array with AJAX (using JSON), my C# handler does not know how to handle the whole query (suddenly the querystrings combine with each other for some reason).
In this example I'm sending a very simple array to the server and the server says the querystring Name is null (but it is not null); Sending any request without the array works fine.
On that note, would appreciate if anyone could explain what the array looks like on the URL (if I wanted to send a request through the browser for example).
AJAX code:
function btnClick() {
var arr = new Array();
arr[0] = "Hey";
arr[1] = "Stackoverflow";
arr[2] = "What's your name?";
var jsonParam = { Name: "test", Pass: "123", Stuff: arr }
$.ajax({
url: "Test.ashx",
type: "get",
data: JSON.stringify(jsonParam),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async:false,
success: function (response) {
alert(response.Name);
}
});
}
Handler code:
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
string res = jss.Serialize(new UserInfo { Name = context.Request.QueryString["Name"], Pass = "pass" + context.Request.QueryString["Pass"], Stuff = new string[] { "1", "2" } });
context.Response.Write(res);
}
You cannot get the json from querystring.
You can use this; You should install NewtonJsonfor JSonConvert from nuget. If you don't want that, you can use JavaScriptSerializer instead of that.
protected object FromJsonToObject(Type t)
{
Context.Request.InputStream.Position = 0;
string json;
using (var reader = new StreamReader(Context.Request.InputStream))
{
json = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject(json, t);
}

jquery ajax not returning data on success c# asp.net

I cant for the life of me figure out why my data being returned is empty. In fiddler i see the json
d=[{"response":[{"h":"h1"},{"h":"h1"}] }]
in fiddler there is a 200 status on the row where i see the json, but no other rows after that one ( maybe its not returning? ). This is the code i am using
$('.SomeLink').click(function () {
var sfn = $('#ID1').val();
var sfp = $('#ID2').val();
var sfi = $('#ID3').val();
var gid = $('#ID4').val();
$.ajax({
type: "POST",
cache: false,
url: '/AjaxHandler.aspx/GetNewHtml',
contentType: "application/json; charset=utf-8",
data: "{'a':'" + sfn + "','b':'" + sfp + "','c':'" + gid + "','d':'" + sfi + "'}",
dataType: "json",
success: function (data) {
alert(data.response[0].h); //acts like a syntax error/no alert box
alert(data); // [object Object]
alert(data.response); // undefined
alert(data.response.count); //acts like a syntax error/no alert box
},
error: function (e) {
alert("Error: " + e.responseText);
}
});
});
AjaxHandler.aspx
[System.Web.Services.WebMethod()]
public static string GetNewHtml(string a, string b, string c, string d)
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "h1"},
new Samp{h = "h1"}
};
return Serialize(new { response = samp });
}
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
Samp Class
public class Samp
{
public string h = "";
}
This is my first time using jquery ajax with asp.net so im sure im missing something that is probably relatively simple. Im using .Net 4.0 , jquery 1.7.1 , iis 7.5
Try data.d for your return object:
alert(data.d);
its tripping over the quotes around the property names. try string indexes.
try
data["response"][0]["h"]
returns h1

Categories

Resources