How to get POST data in WebAPI?

前端 未结 8 1323
天涯浪人
天涯浪人 2020-11-29 21:32

I\'m sending a request to server in the following form:

http://localhost:12345/api/controller/par1/par2

The request is correctly resolved t

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 21:52

    After spending a good bit of time today trying to wrap my brain around the (significant but powerful) paradigm shift between old ways of processing web form data and how it is done with WebAPI, I thought I'd add my 2 cents to this discussion.

    What I wanted to do (which is pretty common for web form processing of a POST) is to be able to grab any of the form values I want, in any order. Say like you can do if you have your data in a System.Collections.Specialized.NameValueCollection. But turns out, in WebAPI, the data from a POST comes back at you as a stream. So you can't directly do that.

    But there is a cool little class named FormDataCollection (in System.Net.Http.Formatting) and what it will let you do is iterate through your collection once.

    So I wrote a simple utility method that will run through the FormDataCollection once and stick all the values into a NameValueCollection. Once this is done, you can jump all around the data to your hearts content.

    So in my ApiController derived class, I have a post method like this:

        public void Post(FormDataCollection formData)
        {
            NameValueCollection valueMap = WebAPIUtils.Convert(formData);
    
            ... my code that uses the data in the NameValueCollection
        }
    

    The Convert method in my static WebAPIUtils class looks like this:

        /// 
        /// Copy the values contained in the given FormDataCollection into 
        /// a NameValueCollection instance.
        /// 
        /// The FormDataCollection instance. (required, but can be empty)
        /// The NameValueCollection. Never returned null, but may be empty.
        public static NameValueCollection Convert(FormDataCollection formDataCollection)
        {
            Validate.IsNotNull("formDataCollection", formDataCollection);
    
            IEnumerator> pairs = formDataCollection.GetEnumerator();
    
            NameValueCollection collection = new NameValueCollection();
    
            while (pairs.MoveNext())
            {
                KeyValuePair pair = pairs.Current;
    
                collection.Add(pair.Key, pair.Value);
            }
    
            return collection;
         }
    

    Hope this helps!

提交回复
热议问题