Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created Web API and trying to consume it within MVC Web Application but the web api methods are calling twice for every request ,MVC application is requesting only one call to web api

What I have tried:

Web Api Method :
C#
[HttpPost]
        [Route("SaveClientDetails")]
        public async Task<httpresponsemessage> AddNewClient([FromBody]usp_GetClientDetails client)
        {
            try
            {
                usp_GetClientDetails result = new usp_GetClientDetails();
                await Task.Run(() =>
                {
                    result = IClientRepository.InsertClientDetails(client);
                });
                return Request.CreateResponse(HttpStatusCode.OK, new { StatusCode = HttpStatusCode.OK, Status = "Success", Data = result });
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new { StatusCode = HttpStatusCode.InternalServerError, Status = "Failed", Data = ex.Message });
            }
        }
Client Calling Web API:
C#
[HttpPost]

        public ActionResult AddClient(ClientAddModel objcltModel)
        {
            var parameters = new usp_GetClientDetails
            {
                ClientMappedTo=Convert.ToInt32(objcltModel.ClientMappedTo),
                UserName="",
                FirstName=objcltModel.FirstName,
                LastName= objcltModel.LastName,
                EmailId= objcltModel.EmailId,
                PrimaryContactNo= objcltModel.PrimaryContactNo,
                SecondaryContactNo= objcltModel.SecondaryContactNo,
                QRCode=Common.CreateQRCodeWithContact(objcltModel.PrimaryContactNo),
                AadharNo= objcltModel.AadharNo,
                PanNo= objcltModel.PanNo,
                Pincode= objcltModel.Pincode,
                City= objcltModel.City,
                IsActive=true,
                CreatedDate=DateTime.Now,
                Deposit=objcltModel.Deposite,
                Area1= objcltModel.Area1,
                Area2= objcltModel.Area2,
                FloorNo= Convert.ToInt32(objcltModel.FloorNo),
                FlatNo= objcltModel.FlatNo,
                BuildingName= objcltModel.BuildingName,
                Rate=objcltModel.Rate

            };
            var result = WebAPIGeneric.GetAPIResponse(WebAPIMethods.SaveClientDetails, parameters, Method.POST, null);
            if(result !=null)
            {
                if(result.Status=="Success")
                {
                    ViewBag.Message = "Client Added Successfully";//JsonConvert.DeserializeObject<usp_getclientdetails>(result.Data.ToString()).Message;
                }
            }
            ViewBag.Userlst = getUserList() == null ? new SelectList(string.Empty) : new SelectList(getUserList().ToList(), "UserId", "FullName");
            return View("Index");
        }
GetAPIResponseMethod :
C#
public static ResponseModel GetAPIResponse(string Url, object data, Method method,Hashtable htable)
        {
            var client = new RestClient(Common.baseUrl);
            var request = new RestRequest(Url, method);
            if(data==null && htable !=null)
            {
                foreach(DictionaryEntry entry in htable)
                {
                    request.AddParameter(entry.Key.ToString(),entry.Value.ToString());
                }
                
                //request.AddParameter("application/json", JsonConvert.SerializeObject(htable), ParameterType.QueryString);
            }
            else
            {
                request.AddJsonBody(JsonConvert.SerializeObject(data));
            }
            
            var x = client.Execute(request);
            return JsonConvert.DeserializeObject<responsemodel>(client.Execute(request).Content);
        }
Response Model Class:
C#
public class ResponseModel
    {
        public int StatusCode { get; set; }

        public string Status { get; set; }

        public object  Data { get; set; }
    }
Posted
Updated 24-Sep-19 7:22am
v2
Comments
Afzaal Ahmad Zeeshan 24-Sep-19 13:20pm    
Best bet would be to debug the function and step through it line by line. Only then you can see when an HTTP request is made.

Ignore the comment, please see Solution 1.

1 solution

That was an easy guess, because you are sending the request 2 times.

C#
var x = client.Execute(request); // <-- first call
return JsonConvert.DeserializeObject<ResponseModel>(client.Execute(request).Content); // <-- Second one here
You need to use,
C#
var x = client.Execute(request);
return JsonConvert.DeserializeObject<ResponseModel>(x.Content); // Use the x here
This would not call the request only once, and use the result of that query.

Also, please excuse any SDK-based errors, since I wrote this code off the top of head, so maybe there would be problems with the structure of the code—also I am unaware of this library.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900