通过webrequest发送对象并在Web服务中接收

时间:2016-10-13 12:03:08

标签: c# asp.net

我想将对象发送到应用程序并从中接收相同的对象。我想发送和接收2个应用程序之间的消息类。这是我的客户代码:

[Serializable]
    public struct Messages
    {
        public string ErrorCode { get; set; }

        public string ErrorMessage { get; set; }

        public MessageType? messageType { get; set; }

        public SendMessageType? sendMessageType { get; set; }

        public string UserCode { get; set; }

        public DateTime MessageDateTime { get; set; }

        public MethodName methodName { get; set; }

        public int? FieldsCount { get; set; }

        public List<KeyValue> Values { get; set; }
    }

    public struct KeyValue
    {
        public string key { get; set; }

        public string value { get; set; }
    }

    public enum MessageType
    {
        Request,
        Reply,
        Reject
    }

    public enum MethodName
    {
        FindShebaFromDeposit = 1,
        BalanceInquery = 2,
        CheckBill = 3,
        BillPayment = 4,
        GetDepositList = 5,
        NormalTransfer = 6,
        GetPersonInfoFromDeposit = 7
    }

    public enum SendMessageType
    {
        way2,
        way3
    }

    public void POST(Messages messages)
    {
        //Serialize the object into stream before sending it to the remote server
        MemoryStream memmoryStream = new MemoryStream();
        BinaryFormatter binayformator = new BinaryFormatter();
        binayformator.Serialize(memmoryStream, messages);

        //Cretae a web request where object would be sent
        WebRequest objWebRequest = WebRequest.Create("http://localhost:13060/Default/Index");
        objWebRequest.Method = "POST";
        objWebRequest.ContentLength = memmoryStream.Length;
        // Create a request stream which holds request data
        Stream reqStream = objWebRequest.GetRequestStream();
        //Write the memory stream data into stream object before send it.
        byte[] buffer = new byte[memmoryStream.Length];
        int count = memmoryStream.Read(buffer, 0, buffer.Length);
        reqStream.Write(buffer, 0, buffer.Length);

        //Send a request and wait for response.
        try
        {
            WebResponse objResponse = objWebRequest.GetResponse();
            //Get a stream from the response.
            Stream streamdata = objResponse.GetResponseStream();
            //read the response using streamreader class as stream is read by reader class.
            StreamReader strReader = new StreamReader(streamdata);
            string responseData = strReader.ReadToEnd();
        }
        catch (WebException ex)
        {
            throw ex;
        }
    }

这是我的服务器代码:

public class DefaultController : Controller
{
    // GET: Default
    [HttpPost]
    public Bussiness.Message.CoreMessage Index(Bussiness.Message.CoreMessage coreMessage)
    {
        Puller.Bussiness.ServiceMessages serviceMessage = new Bussiness.ServiceMessages();
        var file = serviceMessage.CreateRequest(coreMessage);
        return file;
    }
}

消息类serilize并发送到服务器,但在服务器中它是null?

1 个答案:

答案 0 :(得分:2)

您正在以二进制格式对请求正文进行编码,不会直接反序列化。更好的方法是发送JSON格式的请求体,默认情况下由ASP.NET MVC反序列化。

要序列化为JSON,您可以使用各种选项。我正在使用JavaScriptSerializer.Serialize

或者,您可以使用JsonConvert.SerializeObjectDataContractJsonSerializer或您选择的任何其他库序列化为json。

public void POST(Messages messages)
{
    var request = (HttpWebRequest)WebRequest.Create("http://localhost:13060/Default/Index");
    request.ContentType = "application/json";
    request.Method = "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(messages);
        streamWriter.Write(json);
    }

    var response = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}