Pallavi Prasad
Pallavi Prasad

Reputation: 587

Unable to post a new record through fiddler

I now have a problem with posting a record through fiddler. My code is as below:

[HttpPost]
public void AddStudent(Student s)
{
    SqlConnection myConnection = new SqlConnection();
    myConnection.ConnectionString = @"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;";

    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.CommandType = CommandType.Text;
    sqlCmd.CommandText = "INSERT INTO Tbl_Students (Roll_Number,FirstName,LastName,Class,Gender) Values (@Roll_Number,@FirstName,@LastName,@Class,@Gender)";
    sqlCmd.Connection = myConnection;

    sqlCmd.Parameters.AddWithValue("@Roll_Number", s.Roll_Number);
    sqlCmd.Parameters.AddWithValue("@FirstName", s.FirstName);
    sqlCmd.Parameters.AddWithValue("@LastName", s.LastName);
    sqlCmd.Parameters.AddWithValue("@Class", s.Class);
    sqlCmd.Parameters.AddWithValue("@Gender", s.Gender);

    myConnection.Open();
    int rowInserted = sqlCmd.ExecuteNonQuery();
    myConnection.Close();
}

When I run this on fiddler, I am getting a NullException. The response body is not being excepted by the code. The response body is in JSON format. Image as below:

enter image description here

EDIT This is the error I am getting (image).

enter image description here

Upvotes: 1

Views: 119

Answers (2)

Roman Marusyk
Roman Marusyk

Reputation: 24579

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

public void AddStudent([FromBody]Student s)

In this example, Web API will use a media-type formatter to read the value of name from the request body. Here is an example client request.

POST http://localhost:5076/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 7

"{Students}"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

Upvotes: 1

Ricky Keane
Ricky Keane

Reputation: 1700

I would set the Content-Type header as well in Fiddler

Content-Type: application/json

Upvotes: 2

Related Questions