Serializing HttpContext object to store in a datab

2019-07-22 19:41发布

问题:

We have a C# ASP.Net MVC website. I would like to store everything contained in the HttpContext.Current.Request object in a table in SQL Server for later analysis.

I attempted serializing the object into a Byte Array, then storing it in a binary field in SQL Server, however the serializer won't serialize the HttpContext object since it is not marked Serializable.

Is there any way to mark a System.Web class as serializable? Or is there another way to accomplish this?

回答1:

For production code, I don't believe you can change the serialization aspect of the HttpContext. If this is non-production you might try modifying the Assembly to insert the Serializable attribute (but that may need to be done on sub-classes too) using a tool like Reflector and some plug-ins.

What might be an easier option would be to use Reflection to enumerate all the public and private fields. You could convert simple types to their string representation and recurse on classes that are slightly more complicated. You might even be able to find a tool to do this, the idea would probably be referred to ask an Object Graph viewer.



回答2:

I'd advise against storing the entire request, there would be far too much noise.

Instead pick out the signal that you want. That is log specifically what you are interested in, e.g. particular variables.