Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Tuesday, January 31, 2012

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Very recently I have worked on asp.net MVC application. Everything is working fine for MVC v1. But when move to MVC v2 I have gotten this error-

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

After making some r & d I have found the solution:

Reason:

In MVC v2 they block Json for GET requests (as you can tell from the error) for security reasons.

If your JSON payload:

1.Contains sensitive non-public data
2.Returns an Array
3.Responds to a GET request
4.Browser making the request has JavaScript enabled (very likely the case)
5.Browser making the request supports the __defineSetter__ method.

Then the data is vulnerable to a JSON hijacking. Typically, it's not *your* data but the data of the users of your website.

For more details about JSON Hijacking.

Solution:
1.A possible solution I found online is to set the request to "POST" method instead of "GET" method.

2.If you want to override the behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.

public ActionResult Index()
{
//Return Json result using LINQ to SQL

//###################################################
//MVC 1.0 specific implementation - A JSON Result
//is returned.
//###################################################
//return new JsonResult
//{
// Data = (from p in Product.GetProductDataList()
// where p.ColorId == colorid
// select p).ToArray()
//};

//###################################################
//MVC RC2 specific implementation - A JSON Result
//is returned, and the AllowGet property is set for
//the JsonRequestBehavior.
//###################################################
var data = (from p in Product.GetProductDataList()
where p.ColorId == colorid
select p).ToArray();

return Json(data, JsonRequestBehavior.AllowGet);
}

Saturday, February 12, 2011

Handling JSON Arrays returned from ASP.NET Web Services with jQuery

The Web Service methods that I will use revolve around cars. Having set up a web site in Visual Studio 2008, I have added a new item of type "Web Service" to the project, calling it EmpInfoService.asmx. The code-behind - EmpInfoService.cs - is automatically generated within the App_Code folder. The full code for that class file is as follows:

Code: asmx

public class Employee
{
public string FullName;
public string Designation;
public string PhoneNo;
}


/// <summary>
/// Summary description for Emp info
/// </summary>


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


[ScriptService]
public class EmpInfoService : WebService
{
List Employees = new List{
new Employee{FullName="Shakil",Designation="Manager",PhoneNo=5555454},
new Employee{FullName="Ahsan",Designation="Director",PhoneNo=4545454},
new Employee{FullName="Murhsed",Designation="Director",PhoneNo=5454545},
new Employee{FullName="Khurshid",Designation="Officer",PhoneNo=4545545},
new Employee{FullName="Abdul",Designation="Sr.Executive",PhoneNo=45454545},
new Employee{FullName="Yususf",Designation="Sr.Officer",PhoneNo=4545454545},
new Employee{FullName="Farid",Designation="Executive",PhoneNo=45454545},
new Employee{FullName="Munir",Designation="Executive",PhoneNo=454545454},
new Employee{FullName="Foyez",Designation="Executive",PhoneNo=45454545454}
};



[WebMethod]
public List GetAllEmployees()
{
return Employees;
}

[WebMethod]
public List GetEmployeesByName(string name)
{
var query = from c in Employees
where c.FullName == name
select c;
return query.ToList();
}
}


Code: ASPX

The mark-up in the aspx page that will call the Web Service is extremely simple:

<form id="form1" runat="server">
<input type="button" id="btnEmpId" value="Get Employe List" />
<div id="output"></div>
</form>



All that's needed now is some Javascript for the getEmployees() method that has been assigned to the onclick event of the html button. This will go into the <head> section of the page:

First, jQuery is referenced via the src attribute of the first <script> tag. Then a click event is registered with the button which will invoke the getEmployees() function. After that is the getEmployees() function that is fired when the button is clicked.



Jquery:(Without parameter)

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function() {
$('#Button1').click(getEmployees);
});


function getEmployees() {
$.ajax({
type: "POST",
url: "EmployeeService.asmx/GetAllEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var Employees = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>


It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties.
type specifies the HTTP method, which in this case is POST.
url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property.

In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Employee.
The contentType and dataType MUST be specified.
Following this are two further functions: success defines what should be done if the call is successful, and failure handles exceptions that are returned.

In this case, the success callback is passed the resulting HTTP response. In response an object with a property - d - is returned, which contains an array of objects. Each object has a __type property which tells you that it is a Employee object, followed by the other properties of our Web Service Employee object.

The div with the id of output is emptied, in case there was clutter there from a previous ajax call. The jQuery each() function is used to iterate over the collection of objects. Each Employee object is accessed in turn, and its properties are written to a paragraph, which is then appended to the content of div output.

Now, share with you how to send parameter using jquery,
Here we want to filter employee info with employee name from DropDownList

<asp:DropDownList ID="ddlEmpName" runat="server">
<asp:ListItem>Shakil</asp:ListItem>
<asp:ListItem>Ahsan</asp:ListItem>
<asp:ListItem>Murshed</asp:ListItem>
<asp:ListItem>Farid</asp:ListItem>
</asp:DropDownList>

Jquery(with parameter see the bold):

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function() {
$('#Button1').click(getEmployees);
});


function getEmployees() {
$.ajax({
type: "POST",
url: "EmployeeService.asmx/GetEmployeesByName",
data: "{name: " + $('#<%= ddlEmpName.ClientID %>').val() + " }",

contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var Employees = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>

The url option now points to the appropriate method, and a parameter is passed into the data option, which uses jQuery syntax to reference the selected value from the DropDownList. I have used inline ASP.NET tags in this case to dynamically render the ID of the DropDownList using the ClientID property, so that there will be no issues in referencing the DropDownList if this code was transferred to a User Control or another control that implements INamingContainer.

All credits goes to Mr.Mikesdotnetting because I solved my problem from this superb article.

Tuesday, February 9, 2010

Basic Idea on JSON

What is JSON?

JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and object literals. JSON allows communicating with server in a standard way. JSON is used as communication notation instead of XML.

JSON objects are typed while XML data is typeless
1.JSON types: string, number, array, boolean,
2.XML data are all string

JSON stands for Javascript Object Notation which is a data structuring format that is extremely clean and lightweight. Even though JSON is native to javascript (as in, it can be turned into an object directly by javascript), it is quite easy to handle with other languages, making it an ideal replacement of XML when javascript is involved with the exchange of data (i.e. ajax).

var fruitColors =
{
"apple":"green",
"banana":"yellow",
"orange":"orange"
};

alert(fruitColors .apple); //outputs "green"
alert(fruitColors .orange); //outputs "orange"

The above code creates an javascript object bike with two properties apple and orange

JSON Structures
• A collection of name/value pairs
In various languages, this is realized as an object, record,struct, dictionary, hash table, keyed list, or associative array
• An ordered list of values
In most languages, this is realized as an array, vector, list, or sequence

JSON Object Notation
• A JSON object is an unordered set of name/value pairs
• A JSON object begins with { (left brace) and ends with } (right brace)
• Each name is followed by : (colon) and the name/value pairs are separated by , (comma)

For more info please visit:
http://msdn.microsoft.com/en-us/library/bb299886.aspx
http://www.json.org/
http://en.wikipedia.org/wiki/JSON

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...