We have an existing API written in Vb.Net as class library which some of our customers use. Now we want this approach to be changed and expose an web api which in turn will call the class library.
This is how it works, user will pass in method name, class name, parameters for constructor and method as JSON string. Using reflection we have to invoke the class library based on the names passed in. I was able to achieve creating instance of a class and execute the method. Problem is passing parameters for the methods. Because we receive the parameters as json object in API, how to convert this data to type accepted by the methods in class library which we will know only on run time?
[ActionName("invokeapi")]
[HttpPost]
public IHttpActionResult InvokeAPI([FromBody]Newtonsoft.Json.Linq.JObject pClientData)
{
try
{
PostData obj = Newtonsoft.Json.JsonConvert.DeserializeObject<PostData>(pClientData.ToString());
obj.MethodParameter = Newtonsoft.Json.JsonConvert.DeserializeObject(pClientData.GetValue("methodparam").ToString());
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
public class PostData
{
[DataMember(Name = "classname")]
public string ClassName { get; set; }
[DataMember(Name = "methodname")]
public string MethodName { get; set; }
[DataMember(Name = "parameters")]
public string[] Parameters { get; set; }
[DataMember(Name = "methodparam")]
public object MethodParameter { get; set; }
}
Here, data within obj.MethodParameter is of type JArray. How can we convert this to the required type dynamically based on the class name passed in from client (ClassName property).
Aucun commentaire:
Enregistrer un commentaire