Consume Web API POST Method In ASP.NET MVC Using Http Client

In this article, We will learn about how can we consume Web API POST Method in MVC using an HTTP client.

Here, we have already created Web API POST-Method as shown below.

namespace CycleWebAPICodeFirst.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class CycleController : ControllerBase
    {
        private readonly ISqlHelper _sqlHelper;
        private static ResponseModel _response;
        public CycleController(ISqlHelper sqlHelper)
        {
            _sqlHelper = sqlHelper;
        }
       
        [HttpPost("AddCycle")]
        public IActionResult Post(CycleDTO cycleDTO)
        {
            if (ModelState.IsValid)
            {
                Cycle cycle = new Cycle()
                {
                    CycleName = cycleDTO.CycleName,
                    Company = cycleDTO.Company,
                    Price = cycleDTO.Price,
                    Size = cycleDTO.Size,
                    Colour = cycleDTO.Colour,
                    Image=cycleDTO.Image 
                };
                 _cycleContext.Cycle.Add(cycle);
                 _cycleContext.SaveChanges();
                 _response.Message = "Add Successfully";
                 _response.IsSuccess = true;
            }
            else
            {
                _response.IsSuccess = false;
                _response.Message = "Enter Valid Data";
            }
            return Ok(_response);
        }
    }
}

In the above web API, the Post method will handle the POST request “https://localhost:44368/Cycle/AddCycle“. It will store cycle data in the database using Entity Framework and return a boolean value and string message as a response.

Now, We will see how to consume the above already created POST API in ASP.NET MVC using HTTP Client by following the steps.

Step 1. Create a Model class according to what data we are passing with a POST request.

Cycle.cs

public class Cycle
{
    public string CycleName { get; set; }
    public string Company { get; set; }
    public int Price { get; set; }
    public string Colour { get; set; }
    public int Size { get; set; }   
}

Step 2. Now we need to create a controller class called “CycleController.cs” and add an action method called “Create” which will render a view where the user can enter data and submit it.

CycleController.cs

public class CycleController : Controller 
{
 public ActionResult Index()
 { 
   return View(); 
 }
 public ActionResult Create()
 {
  return View();
 }
}

Step 3. Now, Right-click on Create action method and select Add View. It will open a popup which is shown below.

Now, Enter the view name Create and select Create template and select an appropriate model class. Then it will automatically generate a CSHTML file as shown below.

Create.cshtml

@model Test_Consume_web_api.Models.Cycle

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Cycle</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CycleName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CycleName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CycleName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Company, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Company, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Colour, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Colour, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Colour, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Size, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Size, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Size, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

In the above view file, we can see that the form will automatically generate. Users use this form to enter data and send that data to the server side by clicking of create button.

Now run the project and navigate to “http://localhost:63262/Cycle/Create” and it will display the output shown below.

Step 4. When the user enters data using the above form and submits it by clicking on a create button. It will send a POST request to an action method “Create” of the cycle controller. which will handle POST requests and send this request to the web API POST method and get a response from it.

A Create action method is as below,

public class CycleController : Controller
   {
       // GET: Cycle
       public ActionResult Index()
       {
           return View();
       }

       public ActionResult Create()
       {
           return View();
       }

       [HttpPost]
       public ActionResult create(Cycle cycle)
       {
           using (var client = new HttpClient())
           {
               client.BaseAddress = new Uri("https://localhost:44368/Cycle/");

               //HTTP POST
               var postTask = client.PostAsJsonAsync<Cycle>("AddCycle", cycle);
               postTask.Wait();

               var result = postTask.Result;
               if (result.IsSuccessStatusCode)
               {
                   return RedirectToAction("GetCycles");
               }
           }

           ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");

           return View(cycle);
       }
 }

As you can see in the above HttpPost action method create(), it uses HttpClient to send an HTTP POST request to Web API “https://localhost:44368/Cycle/” with Cycle model object. If the response returns success status then it will redirect to the list cycle.

I hope this article will help you to understand how can we consume HTTP POST web API in ASP.NET MVC using an HTTP client.

Thank you.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories