Sending JSON object to the server via http GET

2019-01-26 20:20发布

问题:

I am looking for sending JSON object to the server via GET. Chris's answer on Post an Array of Objects via JSON to ASP.Net MVC3 works for the http POST but not for GET. My case also works for POST but not for GET. What can I do to make GET work Here is my case: in Controller I have the following method public ActionResult Screenreport(Screentable screendata)

   {
       // do something here
       return View();
   }

I have two ModelView as follows:

   public class Screenrecord
   {
      public string Firstname{ get; set; }
      public string Lastname{ get; set; }
   }
   public class Screentable
   {
      public List<Screenrecord> Screenlist { get; set; } 
   }

On the client side I generate JSON object

var Screentable = { Screenlist: screendata };

screendata is an array of Screenrecord

All this work when I use POST but when I use GET I am getting null value (screendata = null) Controllers' method. In other word when click GO, screendata is null in Screenreport(Screentable screendata) routine.

Also, if I send one JSON object it works but if I send an array (list) like I described, it does not. Is what I am trying to do doable?

回答1:

No :-) Thats not how get works.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

(see 9.3 GET)

"The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI"

Request-URI being the important part here. There is no concept of body data in a GET request.



回答2:

Try changing method to public ActionResult Screenreport(HttpRequestMessage request)

Then use below code to get JSON object.

data = request.RequestUri.Query;
data = HttpUtility.ParseQueryString(data).Get("request");



回答3:

Try this example in Javascript:

var someObject = {
   id:123456,
   message:"my message",
}

var objStr = JSON.stringify(someObject);

var escapedObjStr = encodeURIComponent(objStr);

var getUrlStr = "http://myserver:port?json="+escapedObjStr

and now you can forward this URL to your server. I know this is not in any .NET language but you can definitely find the equivalent methods used, or just use the JS right away.