Search code examples
parametersasp.net-web-api2model-binding

How to restrict character set for parameter binding?


I'm in a situation where I have to restrict a web service's character set for route values, query parameters and json body content to latin1.

I've played around with th econtent negotiator, but that one is just for response formatting.

I've tried replacing the supported encodings in the media formatters with one that throws on unexpected characters but when, for instance, the JsonMediaTypeFormatter does its ReadFromStream call, the effectiveEncoding parameter is already the latin1 one and the string is already garbled (I'm trying with some chinese characters).

What I actually want to happen is to create some BadRequest result whenever a wrong encoding gets specified or whenever a non-latin1 character shows up.

Could anybody give me a hint where to look fo the correct place to fix that? I'm sure there must be a better way than to do it all "manually" in a DelegatingHandler.


Solution

  • In the end I just replaced the media formatter with one that validates the string by using Encoding.GetBytes(...) before deserializing into an object.