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

Asp.net Web API Put Method C# Example

Web API Put Method

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

In example we are trying to put a client object to be updated 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(int id, [FromBody]ClientModel client)            
{
    tbClient c = new tbClient();
    c.ClientId = id;
    c.CompanyName = client.CompanyName;
    c.ContactPerson = client.ContactPerson;
    c.Email = client.Email;
    c.Phone = client.Phone;    
        
    //add this details to database            
}
Put with HttpResponseMessage Return type

Put is update method, is almost like Post , the only difference is that this method has Id parameter, for which the data to be updated in database

public HttpResponseMessage Put(int id, [FromBody]ClientModel client) {
try
{
Client c = new Client();
c.ClientId = id;
c.CompanyName = client.CompanyName;
c.ContactPerson = client.ContactPerson;
c.Email = client.Email;
c.Phone = client.Phone;
// update client in database for this clientId
c.ClientId = id;
var returnMessage = Request.CreateResponse(HttpStatusCode.Created, c);
returnMessage.Headers.Location = new Uri(Request.RequestUri + "/" + c.ClientId.ToString());
return returnMessage;
}
catch (Exception ex)
{
   return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}
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);
Test the Put Method with Web Client

Once you are ready with your Put 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 Put Example