简体   繁体   English

通过JSON发送数据

[英]Sending data by JSON

I want to send JSON from desktop application to the server with mvc wepApi. 我想使用mvc wepApi将JSON从桌面应用程序发送到服务器。 this is my desktop application code ,that convert data to the JSON and send it. 这是我的桌面应用程序代码,它将数据转换为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();
    }

and this is my web api 这是我的网络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);
    }

but when post api is calling the Value is null . 但是当post api调用时, Value is null why? 为什么?

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

You are not flushing nor closing the stream, so basically the data never gets to the api. 您既不刷新也不关闭流,因此基本上数据永远不会到达api。

My code: 我的代码:

Program.cs - Console App 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 - some data class UserModel.cs-一些数据类

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

ValuesController.cs - WebApi controller from template 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 - default config with added line about Json, but IT WORKS WITHOUT IT -it's so that I can test GET easily in browser etc. ;) WebApiConfig.cs-默认配置,添加了有关Json的内容,但是没有它,它可以工作-这样我就可以在浏览器等中轻松测试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: 结果:

运行控制台应用程序的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM