简体   繁体   English

ASP.NET C#序列化HttpValueCollection

[英]ASP.NET C# serialize HttpValueCollection

I'm trying to serialize a Request object for logging purposes. 我正在尝试序列化Request对象以进行记录。 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. 谢谢。

In short, trying to serialize a http request object may not end well; 简而言之,尝试序列化http请求对象可能会失败。 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. 对于HttpValueCollection,您可能需要添加某种类型的基本集合,即名称/值对。

Then: populate your new model from the actual request, and serialize your model. 然后:从实际请求中填充新模型,并序列化模型。

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();

If you're interested in the request as a whole (ie: bytes), you can use the HttpRequest.Filter Property . 如果您对整个请求(即字节)感兴趣,则可以使用HttpRequest.Filter属性 It allows to install a filter (an object that derives from Stream) that can read and write from the raw input HTTP request. 它允许安装可以从原始输入HTTP请求读取和写入的过滤器(从Stream派生的对象)。

Here is an article on the subject: Filtering HTTP Requests with .NET 这是有关此主题的文章: 使用.NET过滤HTTP请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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