Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Post Method Example in Asp.net Web API

In this article we will learn how to Post data in Web API

In example we are trying to post a client object to be added in database, just to keep it web API call related I have removed the database calling part ( you can use entityframework, adonet or anything to submit the data to database)
public void Post([FromBody]ClientModel client)
{
tbClient c = new tbClient();
c.CompanyName = client.CompanyName;
c.ContactPerson = client.ContactPerson;
c.Email = client.Email;
c.Phone = client.Phone;

//add this details to database

}

In above code we are simply retrieving the client information from ClientModel object, which is available in [FromBody]. then populate the entity object tbClient to add in database

But there is a problem in above method, we cannot send any message back to client about whether the call was successful or failed or any reason, because the return type is void

Now we see how to write return type as HttpResponseMessage , so that we can send success and error message back to client that will consume this API service
public HttpResponseMessage Post([FromBody]ClientModel client)
{
tbClient c = new tbClient();
c.CompanyName = client.CompanyName;
c.ContactPerson = client.ContactPerson;
c.Email = client.Email;
c.Phone = client.Phone;

// add the new client in database, and get the new clientId

try
{
var returnMessage = Request.CreateResponse(HttpStatusCode.Created, c);
returnMessage.Headers.Location = new Uri(Request.RequestUri.ToString()+ c.ClientId.ToString());
return returnMessage;
}
catch (Exception ex)
{
var returnErrMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
return returnErrMessage;
}
}

Notice the below two lines in above code, creating Response object
var returnMessage = Request.CreateResponse(HttpStatusCode.Created, c);
var returnErrMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);

Once you are ready with your Post method in Web API, you probably need to test if things are working fine, and without creating any complex UI client you can Test Web API
Comment
Name Email Website
Subscribe
 
Asp.Net Web API Post Example


Group Training