简体   繁体   中英

C# Web API REST Service POST

I originally asked a question regarding a WCF web service that I was trying to write and then found that the ASP.net web API was more appropriate to my needs, due to some feedback on here.

I've now found a good tutorial that tells me how to create a simple REST service using Web API which works well pretty much out of the box.

My question

I have a POST method in my REST service server:

    // POST api/values/5
    public string Post([FromBody]string value)
    {
        return "Putting value: " + value;
    }

I can POST to this using POSTER and also my C# client code.

However the bit I don't understand is why I have to prepend an '=' sign to the POST data so that it reads: "=Here is my data which is actually a JSON string"; rather than just sending: "Here is my data which is actually a JSON string";

My C# Client that talks to the REST service is written as follows:

 public string SendPOSTRequest(string sFunction, string sData)
    {
        string sResponse = string.Empty;

        // Create the request string using the data provided
        Uri uriRequest = GetFormRequest(m_sWebServiceURL, sFunction, string.Empty);
        // Data to post
        string sPostData = "=" + sData;
        // The Http Request obj
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriRequest);
        request.Method = m_VERB_POST;
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(sPostData);
        request.ContentLength = byteArray.Length;
        request.ContentType = m_APPLICATION_FORM_URLENCODED;                

        try
        {
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    sResponse = reader.ReadToEnd();
                }                    
            }
        }
        catch (WebException ex)
        {
             //Log exception
        }

        return sResponse;
    }

    private static Uri GetFormRequest(string sURL, string sFunction, string sParam)
    {
        StringBuilder sbRequest = new StringBuilder();
        sbRequest.Append(sURL);

        if ((!sURL.EndsWith("/") &&
            (!string.IsNullOrEmpty(sFunction))))            
        {
            sbRequest.Append("/");
        }
        sbRequest.Append(sFunction);

        if ((!sFunction.EndsWith("/") && 
            (!string.IsNullOrEmpty(sParam))))
        {
            sbRequest.Append("/");
        }
        sbRequest.Append(sParam);

        return new Uri(sbRequest.ToString());
    }

Is anybody able to explain why I have to prepend the '=' sign as in the above code ( string sPostData = "=" + sData; )?

Many thanks in advance!

The content type x-www-form-urlencoded is a key-value format. With form bodies you are only able to read a single simple type from a request body. As a name is expected, but in this case not allowed, you have to prefix the equal sign to indicate that there is no name with the followed value.

However, you should lean away from accepting simple types within the body of your web-api controller actions.

You are limited to only a single simple type if you attempt to pass data in the body of an HttpPost/HttpPut without directly implementing your own MediaTypeFormatter, which is unlikely to be reliable. Creating a light-weight complex type is generally much more preferable, and will make interoperating with other content-types, like application/json , much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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