Passing an Interface as a parameter to Web API method

37349445 11 Reputation points
2021-07-17T11:34:54.403+00:00

Hi All,

I would like to know how can I pass an interface as a parameter to a Web API method. Here's my interface:

public interface IPerson
    {
        string Gender { get; set; }
        decimal Weight { get; set; }
    }

I am sending this information from an MVC method which in turn calls the Web API method, here's the MVC method

[HttpPost]
        public async Task<ActionResult> CallApiAddPerson(string gender, decimal weight)
        {

            string Baseurl = "myAddress";

            var payload = new Dictionary<string, decimal>
                {
                  {"Gender", gender},
                  {"Weight", Weight}
                };

            string strPayload = JsonConvert.SerializeObject(payload);
            HttpContent mContent = new StringContent(strPayload, Encoding.UTF8, "application/json");

            var client = new HttpClient();
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var credentialString = Newtonsoft.Json.JsonConvert.SerializeObject(payload, Formatting.None);


            var response = client.PostAsync("api/MyApi/AddPerson", mContent).Result;
            response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {

            }

            return View();
        }

And here is my Web API method that gets called

[System.Web.Http.HttpPost]
[System.Web.Http.AcceptVerbs("GET", "POST")]
public void AddPerson(IPerson person)
{

}

The problem is that in my Web API method IPerson person always comes up as null, how do I pass in the interface.

Also how do I read the data from the request body?

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET ASP.NET API
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2021-07-17T17:12:23.78+00:00

    Unless you write a custom binder, you can not use an interface as a webapi parameter. As interfaces are abstract and have no constructor, the framework can not create an instance to deserialize to.

    You should use POCO objects for webapi parameters, and all the properties should be value types or POCO.

    Note: it is a good practice to have a separate project that defines the parameters and return types, that can be shared.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.