json call with C#

前端 未结 5 1150
醉话见心
醉话见心 2020-12-04 22:08

I am trying to make a json call using C#. I made a stab at creating a call, but it did not work:

public bool SendAnSMSMessage(string message)
{
    HttpWebR         


        
5条回答
  •  余生分开走
    2020-12-04 22:45

    If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json

    Json(someDictionaryObj, JsonRequestBehavior.AllowGet);
    

    Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5

    as for your web request...it seems ok at first glance..

    I would use something like this..

    public void WebRequestinJson(string url, string postData)
        {
        StreamWriter requestWriter;
    
        var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.Method = "POST";
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.Timeout = 20000;
    
            webRequest.ContentType = "application/json";
            //POST the data.
            using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                requestWriter.Write(postData);
            }
        }
    }
    

    May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

提交回复
热议问题