Web API - debugging shows confusing information

巧了我就是萌 提交于 2019-12-25 07:06:29

问题


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);


来源:https://stackoverflow.com/questions/35339306/web-api-debugging-shows-confusing-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!