POST string to ASP.NET Web Api application - returns null

前端 未结 7 1649
有刺的猬
有刺的猬 2020-11-28 08:05

Im trying to transmit a string from client to ASP.NET MVC4 application.

But I can not receive the string, either it is null or the post method can not be found (404

7条回答
  •  盖世英雄少女心
    2020-11-28 08:27

    I use this code to post HttpRequests.

    /// 
            /// Post this message.
            /// 
            /// URL of the document.
            /// The bytes.
            public T Post(string url, byte[] bytes)
        {
            T item;
            var request = WritePost(url, bytes);
    
            using (var response = request.GetResponse() as HttpWebResponse)
            {
                item = DeserializeResponse(response);
                response.Close();
            }
    
            return item;
        }
    
        /// 
        /// Writes the post.
        /// 
        /// The URL.
        /// The bytes.
        /// 
        private static HttpWebRequest WritePost(string url, byte[] bytes)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
    
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            Stream stream = null;
            try
            {
                request.Headers.Clear();
                request.PreAuthenticate = true;
                request.Connection = null;
                request.Expect = null;
                request.KeepAlive = false;
                request.ContentLength = bytes.Length;
                request.Timeout = -1;
                request.Method = "POST";
                stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
            }
            catch (Exception e)
            {
                GetErrorResponse(url, e);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }
            }
            return request;
        }
    

    In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)

    update

    I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

    On the server, try getting the bytes from stream. The following code is what I use.

         ///  Gets the body. 
         ///  The body. 
         protected byte[] GetBytes()
         {
           byte[] bytes;
            using (var binaryReader = new BinaryReader(Request.InputStream))
            {
                bytes = binaryReader.ReadBytes(Request.ContentLength);
            }
    
             return bytes;
         }
    

提交回复
热议问题