ReZa
ReZa

Reputation: 1283

Receiving JSON Using Asp.net webform or WCF

how can i receive JSON data that is sent to the server using POST ? for example : i want to write a web service that receives JSON form the clients and save it to the DB.

Upvotes: 0

Views: 601

Answers (2)

EdSF
EdSF

Reputation: 12341

Trivial example in WCF:

public interface IHelloWorld
{
    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]        
    HelloWorldResponse Hello(HelloWorldAsk request);
}

DataContracts

[DataContract]
public class HelloWorldAsk
{
    [DataMember]
    public string MyName { get; set; }
    [DataMember]
    public string MyEmail { get; set; }
}

[DataContract]
public class HelloWorldResponse
{
    [DataMember]
    public string YourName { get; set; }
    [DataMember]
    public string YourId { get; set; }
}

Implementation (Service1.svc):

public class Service1 : IHelloWorld
{

    public HelloWorldResponse Hello(HelloWorldAsk request)
    {
        //Do what you need to do - e.g. verify then save to db

        return new HelloWorldResponse
        {
            YourId = request.MyEmail,
            YourName = request.MyName
        };
    }
}

Client: Web page using JQuery (slightly modified from above linked sample):

var $data = JSON.stringify({ "MyName": "Ed", "MyEmail": "[email protected]" });

function CallHandler() {
    $.ajax({
        url: "Service1.svc/hello", //Service.svc is the wcf service, Hello is the service method you are invoking
        contentType: "application/json; charset=utf-8",
        type: 'POST',
        dataType: "json",
        data: $data,
        success: OnComplete,
        error: OnFail
    });
    return false;
}

function OnComplete(result) {
    alert("Your name is: " + result.YourName + " and your email is: " + result.YourId);
    console.log(result);
}
function OnFail() {
    alert('Request Failed');
}

To test call CallHandler() anywhere in the web page.

Response: {"YourId":"[email protected]","YourName":"Ed"}

Response Header:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8

Hth...

Upvotes: 2

Anton Gogolev
Anton Gogolev

Reputation: 115691

In "classic" ASP.NET you can always resort to an IHttpHandler that would handle a "raw" HTTP request. See this question.

Upvotes: 2

Related Questions