using c# webrequest to interact with an asp.net mvc 3 website

青春壹個敷衍的年華 提交于 2019-12-22 09:45:58

问题


I created a simple mvc3 site with a home controller with these actions.

public JsonResult Param(string id)
        {
            string upper = String.Concat(id, "ff");
            return Json(upper);
        }
        public ContentResult Param2(string id)
        {
            string upper = String.Concat(id, "ff");
            return Content( upper);
        }
        public JsonResult Param3(string id)
        {
            string upper = String.Concat(id, "ff");
            io gg = new io();
            gg.IOName = upper;
            return Json(gg);
        }
    }
    public class io
    {
         public string IOName {get;set;}
    }

How do I use c# webrquest to get the json and post to these action urls???


回答1:


Darin's answer is good... but if you are looking to get the result from your method that returns a JSON payload, and you'd like that in C#... I'd do this:

var client = new WebClient();

var result = client.DownloadString("http://foo.com/home/param3/SomeID");

var serialzier = new JavaScriptSerializer();

io MyIOThing = serialzier.Deserialize<io>(result);

From there, you can have access to MyIOThing.IOName.

The JavaScriptSerializer is in the System.Web.Extensions assembly, in the System.Web.Script.Serialization namespace.




回答2:


A WebClient is much easier than a WebRequest:

using (var client = new WebClient())
{
    var data = new NameValueCollection
    {
        { "id", "123" }
    };
    byte[] result = client.UploadValues("http://foo.com/home/param", data);
}


来源:https://stackoverflow.com/questions/7779824/using-c-sharp-webrequest-to-interact-with-an-asp-net-mvc-3-website

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