Free Web Development Online Tutorials, Learn to Code
Asp net web api http post frombody example in C#, Asp.Net Core Web API Post async method example

Asp.net Web API Post Method Example

Asp.net web api client post, In this article you will learn how to Post form-data in Web API

Web API Post FormBody

In example below, 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

Asp.Net Core Web API Async Post Example

Now we see how to post asynchronously in WEB API, this piece of code is written in Asp.net Core 3.1 framework, where we return an HttpResponseMessage object asynchronously based on success or failure.

Web API Error handling become easier because of it’s return type HttpResponseMessage, you can see in below example how to write try catch block and return accurate error message in case of failure, you also can implement multiple catch block to handle different type specific failure.

[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]StudentModel model)
{
    Student _student = new Student();
    _student.StuId = model.StuId;
    _student.FirstName = model.FirstName;
    _student.Email = model.Email;
    _student.Cotact = model.Cotact;
    _student.City = model.City;

    HttpResponseMessage returnMessage=new HttpResponseMessage();


try {
    // add details to database;
    string message = ($"Student Created - {_student.StuId}");
    returnMessage = new HttpResponseMessage(HttpStatusCode.Created);
    returnMessage.RequestMessage = new HttpRequestMessage(HttpMethod.Post, message);
    }
    catch (Exception ex)
    {
    returnMessage = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
    returnMessage.RequestMessage = new HttpRequestMessage(HttpMethod.Post, ex.ToString());
    }


    return await Task.FromResult(returnMessage);
}

In asp.net core, HttpResponseMessage new instance created differently than earlier framework, now in same HttpResponseMessage object you can set the success or failure message, you don’t need to create a new instance.

Comment
Name
Email
Website
Subscribe
 
Web API Post Example

C# web service interview questions


Asp.Net C# Web API Examples | Join Asp.Net MVC Course