Hire ASP Developer
in ASP .NET

Json output using post method in webapi

images
by | 23 Sep 2013

Review of:
Product by:
Hire ASP Developer

Reviewed by:
Rating:
5
On September 23, 2013
Last modified:October 7, 2014

Summary:

Introduction to Web Api:

  • Web API is an easy Asp.net framework which is used to build HTTP services that reach a broad range of clients, including browsers and mobile devices. This framework is an ideal platform for building REST full applications on the .NET Framework.
  • REST: REST (Representational State Transfer) is a simple stateless architecture that generally runs over HTTP.                                                                                    REST is an “architectural style” that basically exploits the existing technology and protocols of the Web, including HTTP (Hypertext Transfer Protocol) and XML. REST is simpler to use than the well-known SOAP (Simple Object Access Protocol) approach, which requires writing or using a provided server program (to serve data) and a client program (to request data).

Introduction to json:

  • JSON Stands for JavaScript Object Notification. It is lightweight text-data interchange format. It  is language independent and self-describing, which make it easy to understand.
  •  Example :
    {
    “age”:55,
    “Name”:”mkyoung.com”
    “Message”:["msg 1","msg 2","msg 3"]
    }

How to create Api:

  • in your MVC application create an api controller using add new item option.
  • In controller implement action for example Login.
  • Login action consumes parameter as Username and Password and give the information of user if the login details are correct.
  • Here is the code (for example):


public class UserController : ApiController
{
[HttpPost]
[ActionName("LoginProcess")]
public dynamic LoginProcess(Pro_UserMasterForiPhone User)
{
Pro_UserMasterForiPhone obj_Pro_UserMasterForiPhone = new DAL_UserMaster().LoginProcessFromiPhone(User.UserName,User.Password);
if (obj_Pro_UserMasterForiPhone.Result == "Success")
return obj_Pro_UserMasterForiPhone;
else
{
var dictionary = new Dictionary<string, dynamic>();
dictionary.Add("Result", obj_Pro_UserMasterForiPhone.Result);
return dictionary;
}
}
}

  • It returns output in XML format but you can change it to JSON by doing setting in WebApiConfig.cs Located in App_Start folder in your application.
  •  You need to write following code in Register Method of WebApiConfig.cs file to get json output.

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

Leave a Reply