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(开发者_JAVA技巧System.String) at all levels of their inheritance hierarchy. System.Web.HttpValueCollection does not implement Add(System.String).
How to solve the problem? Thanks.
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.
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
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();
精彩评论