Free Web Development Online Tutorials, Learn to Code
Learn Web Api Development, Web API C# Tutorial, Web API Security, Authentication, Authorization

Web API Post Method Example Asp.net C#

Web API Post FormBody

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 this tutorial web API call specific, I have removed the database calling part ( you can use Entity Framework , Ado.net 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

Return HttpResponseMessage

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;
    }
}
Return CreateResponse and CreateErrorResponse

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);
Now Test Web Client

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
 
Web API Post Example

C# web service interview questions