Filter to delete control characters from incoming strings

I have a SS WS which creates XML files. Sometimes the incoming strings include non-printable characters like 0x1F which are invalid for XML. I could validate each string before serializing to XML, but I wonder if it would be easier to add a filter to SS which replaces all 0x1F chars with a blank space in all fields of type string.

If so, Is there sample code showing how to add a filter like this to SS?


For adhoc requests you can take over deserializing the Request with a Custom Request Binder or by implementing IRequiresRequestStream but you wouldn’t want to do this for every Services.

If you want to do this for all XML Content Types than probably the easiest solution is to take over the XML Content Type and add any pre-processing you need before sending it to the XmlSerializer, e.g:

    (req, res, stream) => XmlSerializer.SerializeToStream(res, stream),
    (type, stream) => XmlSerializer.DeserializeFromStream(type, stream));

Where you’ll pass in a modified Stream instead of the existing stream.

Another option is to buffer the Request Stream and replace the contents of the Request Body with the rewritten XML, e.g:

this.PreRequestFilters.Add((req, res) =>
    var httpReq =  req as AspNetRequest;
    if (httpReq != null && req.RequestAttributes.HasFlag(RequestAttributes.Xml))
        var existingBody = req.GetRawBody();
        var newBody = existingBody.Replace(badChar, " ");
        httpReq.BufferedStream = new MemoryStream(newBody.ToUtf8Bytes());

Note: this assumes an ASP.NET Host if you want to use this for self-hosts you need to cast to ListenerRequest instead.

1 Like

Last option should do it, thanks for the code, great starting point.