pistacchio
pistacchio

Reputation: 58903

ASP.NET C# serialize HttpValueCollection

I'm trying to serialize a Request object for logging purposes. The code

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
// obj is a Request object

gives me the following exception:

To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.String) at all levels of their inheritance hierarchy. System.Web.HttpValueCollection does not implement Add(System.String).

How to solve the problem? Thanks.

Upvotes: 1

Views: 1610

Answers (3)

Tony
Tony

Reputation: 1307

I didn't try it but this would likely work and would be available to serialize.

HttpContext.Current.Request.GetType()
                .GetProperties()
                .Select(
                    a =>
                        new KeyValuePair<object, object>(a, HttpContext.Current.Request.GetType().GetProperty(a.GetType().Name)))
                .ToList();

Upvotes: 0

Simon Mourier
Simon Mourier

Reputation: 139095

If you're interested in the request as a whole (ie: bytes), you can use the HttpRequest.Filter Property. It allows to install a filter (an object that derives from Stream) that can read and write from the raw input HTTP request.

Here is an article on the subject: Filtering HTTP Requests with .NET

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063569

In short, trying to serialize a http request object may not end well; even if you get past the current issue, I would expect it to fail in a few more places.

You should construct your own object model that includes those parts of the request you care about, in a simple form. In the case of the HttpValueCollection, you may need to add a basic collection of some type that is a name/value pair.

Then: populate your new model from the actual request, and serialize your model.

Upvotes: 1

Related Questions