Send JSON data to ASP.NET HTTP Handler - asp.net

i have an ASP.NET 4.0 HTTP handler that should receive and send data in json format. I'm using jquery to send json objects serialized in a string to the handler. It correctly sends the request but i don't know how i could retrieve the data from the httpcontext passed to the handler and how i could deserialize it... Can someone help me?
UPDATE 1
$.ajax({
type: "POST",
url: "myurl.ashx",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: $.toJSON({
...
}),
success: function (response) {
...
}
});

Do you send the data from jquery as a POST or GET request? In your Http Handler you can retrieve the values through the HttpContext.Request either via Forms or QueryString
ie. string json = HttpContext.Current.Request.Forms["json"];
To deserialize you can use the built in System.Web.Script.Serialization.JavaScriptSerializer class like this
string json = HttpContext.Current.Request.Forms["json"];
var js = new JavaScriptSerializer();
YourType obj = js.Deserialize<YourType>(json);

Related

Do I need to sanitize user string input on a ASP.NET API Endpoint? If so how?

I wrote a service that converts English to Pig Latin for my website. It's a API endpoint that gets a string posted to it.
I'm concerned that because anything can be sent by the user, unsafe code could somehow be sent and run on the server.
Do I need to sanitize the input under these circumstances?
//Here is the API Action.
[HttpPost]
[ResponseType(typeof(string))]
[Route("api/plconverter")]
public IHttpActionResult TranslateIntoPigLatin([FromBody]string english)
{
string piglatin = convert_to_pig_latin(english);
return Ok(piglatin);
}
//Here is the AJAX call that gets made.
$.ajax({
url: "/api/plconverter",
type: "POST",
data: JSON.stringify(($(this).val().trim())),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#pig_latin_output").html(data);
}
});

Jil serializer as MVC default, don't accept "json" ContentType

Does any one know if Jil can accept ContentType: 'application/json' in the http call to the API?
From what I see it can only accept ContentType:x-www-formencoded
An example of what don't work for me, the object received in the controller is null.
This is the JS call
var request = $.ajax({
url: uri,
type: commad,
data: JSON.stringify(obj),
dataType: "json",
contentType: 'application/json',
This is the obj content:
{"SessionToken":"65e2be91-a455-0ef3-0ba0-c2dd2c281ecc","ClientType":1,"OfferType":1,"DeviceInfo":{"Width":1080,"Height":1920}}
Now, in the MVC controller this is the method:
[HttpPost]
public Task<ActionResult> GetUserOffers([FromBody]OffersRequestInfo obj)
{
if (obj == null)
return null;
CampaignLogic logic = new CampaignLogic();
Task<ActionResult> res = logic.GetOffers(obj);
return res;
}
the obj parameter received as null when using Jil, with Newtonsoft it is holding the value from the request.
The next line should be added to the constractor of the JilFormatter
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
More explanation on how to implement Jil as the default mvc serializer:
Here

How to get post data as json in asp.net?

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});
You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

Send AJAX request to .aspx page and return JSON

I know that it is possible to send an AJAX request to an .asmx page. And I also know that an .asmx page handles an AJAX request via a web method.
Is it also possible to send an AJAX request to an .aspx page? If so, does an .aspx page also handle an AJAX request via a web method? Note that I would like to return a JSON response from the .aspx page. Is this possible?
You can define web methods in the code-behind of your .aspx page and then call them:
[WebMethod]
public static string doSomething(int id)
{
...
return "hello";
}
And then, to call a web method in your jQuery code:
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
Here is a good link to get started.
if i understood question correctly, Aspx is same as HTML. It will be rendered as HTML. but only difference is Server Side and Controls retaining the states with state mechanism.
so you can do jquery $.ajax() function.
$.ajax({
url: UrlToGetData,
dataType:'json',
success:function(data){
//do some thing with data.
}
});
or if you want to write out json value to the response, then use Response.ContentType
first use any Javascript serializer(JSON.NET) , then set the contentType like this.
Response.ContentType="application/json";
$.ajax({
url: "(aspx page name/method to be called from the aspx.cs page)",
type: "POST",
dataType: "json",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
//TO DO after success
}
});
Try the above code

Whats the best way to send array of objects from javascript to webservice?

I have in my javascript these 2 functions "classes":
// product class
function Product() {
this.id;
this.qty;
this.size;
this.option;
}
// room class
function Room() {
this.id;
this.type;
this.products = [];
}
I have my js logic which fills rooms and their products.
Now i want to send array of rooms to a webservice to do some calculations and get back from it the result.
How to send this array objects to the service and whats the data type which the service will receive to loop through and process?
I tried to write the javascript code like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: "{'rooms':'" + roomsObjects + "'}",
dataType: "json",
success: function(result) {
alert(result.d);
}
});
And the webservice like this:
[WebMethod]
public string CalculatePrices(object rooms)
{
return "blabla";
}
but i find that rooms in the wbservice is always = [object Object]
For that case this would work:
//...
data : '{"rooms":[' + roomsObjects.join() + ']}',
//...
The above code will generate a valid JSON string, but I recommend you to get a JSON library and use JSON.stringify function:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: JSON.stringify({'rooms': roomsObjects}),
dataType: "json",
success: function(result) {
alert(result.d);
}
});
If you don't mind including a tiny JavaScript library, I think using json2.js' JSON.Stringify is the best way to serialize objects for use with ASP.NET AJAX services.
Here's a snippet from that post:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var NewPerson = { };
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/AddPerson",
data: JSON.stringify(DTO),
dataType: "json"
});
There's no array in that example, but JSON.Stringify does serialize JavaScript arrays in the correct format to send in to ASP.NET AJAX services for array and List parameters.
A nice thing about using JSON.Stringify is that in browser that support native JSON serializing (FF 3.5, IE 8, nightly builds of Safari and Chrome), it will automatically take advantage of the browser-native routines instead of using JavaScript. So, it gets an automatic speed boost in those browsers.
Change:
data: "{'rooms':'" + roomsObjects + "'}",
to:
data: {'rooms':roomsObjects},

Resources