Web API - debugging shows confusing information

2019-09-09 21:18发布

问题:

I've already got help here and here with my Web API, but now I think I've arrived to the edge of a Grand Canyon... Fortunately my execution by my boss was postponed, but sentence was not yet commuted. So any suggestions appreciated wholeheartedly, especially since my newbie status in the stuff hasn't yet changed.

So, the code is as shown in second linked question (can post it here, but I think it would be redundant). I've corrected errors with SQL link, so it now doesn't crash when trying to call procedure, set up debug enviro and started testing.

I'm sending a POST request (with JSON in payload) using ARC extension in Chrome while debugging and I have an error message:

However, after changing code using suggestions from answers and comments to this:

namespace NA.Controllers
{
    public class NotesController : ApiController
    {

        [Route("AddNote")]
        [HttpPost]
        public HttpResponseMessage PostNote()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            StreamReader stream = new StreamReader(HttpContext.Current.Request.InputStream);
            string jsonData = stream.ReadToEnd();
            System.IO.File.WriteAllText(@"C:\temp\BLZ_content.txt", jsonData);
            return response;
        }

    }
}

I get a success, correct response and json is being saved to a file. So API in general works fine. This, in turn, means that my code for deserialize json (or just capturing it from body) is not.

回答1:

You can not read incoming data from the response object you just created. You have to read it from the Request like this:

string jsonData = new StreamReader(Request.InputStream).ReadToEnd();

Then you can log it to the file to see if you are getting what you are expecting to get. If you do, you can then deserialize manually jsonData to List like this:

List<Note> response = JsonConvert.DeserializeObject<List<Note>>(jsonData);