首页 > 解决方案 > How to convert Object and view it on WebAPI?

问题描述

Here is my question, I got a Web API and client(winform), client will send out data with a Serialize Object. My Web API do have received and return a response to client. But I can't view the data on Web API, I do have try using Deserialize Object and convert it into string but not working neither. Please help me,Thanks!

Here is my code:

Client

 private string WebApiPost(string sParam, string sJson)
    {
        var client = new HttpClient();
        var content = new StringContent(sJson, Encoding.UTF8, "application/json");
        var response = client.PostAsync(sWebAPI_URL + sParam, content).Result;
        var body = response.Content.ReadAsStringAsync().Result;
        return body;
    }

This is my Web API

public object Post([FromBody]object hL7)
    {

        //what should I do???
        //I've tried set hL7 into string but it wont get any data;
        //I've also tried deserialize it but will get 500 internal server error.
        return hL7;
    }

This is my WebAPI model

public class HL7MID
{
    public string LOC { get; set; }
    public string COMPANY { get; set; }
}

public class HL7MID_List
{
    public string sMSG { get; set; }
    public List<HL7MID> data = new List<HL7MID>();
}

标签: c#jsonasp.net-web-apiasp.net-web-api2asp.net-core-webapi

解决方案


因为sJsonmatches HL7MID,您可以使用该类型作为Post函数的参数,并且只使用该类型。

public HL7MID Post([FromBody]HL7MID hL7)
{
    //use hL7 here
    return hL7;//also since you know the return type, changing that to HL7MID is suggested
}

推荐阅读