简体   繁体   中英

C# Web api getting POST data from JSON

I have an issue that I've been trying to solve. I'm trying to send data from a java application to a web server, but I can't figure out how to actually send it. The java code is as follows:

String hStr = "{\"id\":2,\"name\":\"John\",\"height\":36.72342538,\"width\":2.99999998,\"frequency\":871.07,\\"idList\":[],\"level\":0.0}";

House ap = toJsonMap.readValue(hStr, House.class);
when: "ask the server to add a house from the request"
def response = server.httpClient.requestSpec { spec ->
    spec.body { b -> 
    b.text(hStr) 
    b.type("application/json")
    }
} 
.post("//modeling/housing/{hid}/prop/point/in");

I then have the C# read this code like this:

    [Route("modeling/housing/{hid}/prop/point/in")]
    [HttpPost]
    public HttpResponseMessage AddPoint(int hid, int id, string name, double height, double width, double frequency, List<int> idList, double level)
    {
        DAL.House h = new DAL.House();

        try
        {
            using (DAL.Entities context = DAL.Entities.CreateContextForComplex(said))
            {
                if (!context.Houses.Where(a => a.Id == id).Any())
                {

                    h.Name = name;
                    h.Height = height;
                    h.Width = width;
                    h.Frequency = frequency;
                    h.IdList= idList;
                    h.Level = level;
                    h.LastModified = System.DateTime.UtcNow;

                    context.Houses.Add(ap);
                    context.SaveChanges();

                    return Request.CreateResponse(HttpStatusCode.OK, ap);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Housing id already exists");
                }
            }
        }
        catch (EntityException)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, "Entity Exception");
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
        }
    }

I just can't figure out how to get the data from this post. Particularly getting all of the different types of variables. I found a lot of different answers, but nothing seems to work.

Most likely you need to create a class that has properties matching the incoming request post body's object properties. For example:

public class House
{
  public int Hid { get; set; }
  public int Id { get; set; }
  public string Name { get; set; }
  public double Height { get; set; }
  public double Width { get; set; }
  public double Frequency { get; set; }
  public List<int> IdList { get; set; }
  public double Level { get; set; }
}

Then you would update your method signature as follows:

public HttpResponseMessage AddPoint(House house)

Try to create a class that represents all the properties in the JSON Object:

public class YouClass
{ 
    public int Id { get; set; }
    public string Name { get; set; }
    public string Height { get; set; }
 ......
    // add others
 }

Then in your controller:

public class HousingController : ApiController
 {
    [Route("AddPoint")
    [HttpPost]
    public HttpResponseMessage AddPoint([FromBody] YourClass)
    {

    }
}

Then modify the URL of API your are calling:

.post("api/Housing/Addpoint")

Your URL might be different, you might use : http://localhost:Port/api/Housing/Addpoint and the port. Make sure you try it in browser first or use Postman. Check this

.post("//modeling/housing/{hid}/prop/point/in");

This line of code should give you a timeout in your java, if this is exactly how you have it typed. What you really want here is something more like:

.post("http://localhost:PortNumber/modeling/housing/"+ ap.id +"/prop/point/in");

Where PortNumber is the port your web api is running on, and ap.Id is the Id of the record you are trying to modify.

After you have corrected your endpoint situation, then move on to the other answers and use JSON.Net to deserialize your JSON back into a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM