question

37349445 avatar image
2 Votes"
37349445 asked Bruce-SqlWork answered

Passing an Interface as a parameter to Web API method

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?

dotnet-aspnet-core-mvcdotnet-aspnet-core-webapidotnet-aspnet-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.