通过JSON发送数据

时间:2015-02-11 15:05:34

标签: json model-view-controller asp.net-web-api

我想通过mvc wepApi将JSON从桌面应用程序发送到服务器。 这是我的桌面应用程序代码,它将数据转换为JSON并发送它。

 private void btnAddUserType_Click(object sender, EventArgs e)
    {
       UserType userType = new UserType();
        userType.UserTypeName = txtUserTypeName.Text;

        string json = JsonConvert.SerializeObject(userType);


        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
        streamWriter.Write(json);


        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        var streamReader = new StreamReader(httpResponse.GetResponseStream());
        var responseText = streamReader.ReadToEnd();
    }

这是我的网页api

 // POST api/default1
    public void Post([FromBody]string value)
    {
        UserTypeRepository bl = new UserTypeRepository();
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
        MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
        UserType u = new UserType();
         u = (UserType)js.ReadObject(stream);
        bl.Add(u);
    }

但是当post api正在调用Value is null时。 为什么呢?

1 个答案:

答案 0 :(得分:2)

        using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            streamWriter.Write(json);

你没有刷新或关闭流,所以基本上数据永远不会到达api。

我的代码:

Program.cs - 控制台应用

class Program
{
    static void Main(string[] args)
    {
        var user = new UserModel {Id = 4, FirstName = "Michael", LastName = "Angelo"};
        var json = JsonConvert.SerializeObject(user);
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:56506/api/Values/");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            streamWriter.Write(json);



        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        var streamReader = new StreamReader(httpResponse.GetResponseStream());
        var responseText = streamReader.ReadToEnd();
        Console.WriteLine(responseText);
        Console.ReadKey();
    }
}

UserModel.cs - 一些数据类

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }
}

ValuesController.cs - 来自模板的WebApi控制器

public class ValuesController : ApiController
{
    // GET api/values
    public UserModel[] Get()
    {
        return UserProvider.Instance.Get(); // returns some test data
    }

    // GET api/values/5
    public UserModel Get(int id)
    {
        return new UserModel{Id=1,FirstName="John",LastName="Smith"};
    }

    // POST api/values
    public void Post([FromBody]UserModel value)
    {
        if (value == null)  // BREAKPOINT HERE, just to see what's in value
        {
            var x = value;
        }
    }

}

WebApiConfig.cs - 默认配置添加了关于Json的行,但是IT工作没有IT - 因此我可以在浏览器中轻松测试GET;)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

结果:

Result of running console app