DecoderFallbackException : Unable to translate bytes

The error Unable to translate bytes is a peculiar one if you're not familiar with what goes on under the covers when a string with special characters is deserialized.

    2018-04-24 13:53:33.2637 | Error][32] Method: POST
    URL: http://local/api/v1/pageresponses
    An error occured deserializing model state
    Action Parameters :{
      "exception": {
        "ClassName": "System.Text.DecoderFallbackException",
        "Message": "Unable to translate bytes [E5] at index 424 from specified code page to Unicode.",
        "Data": null,
        "InnerException": null,
        "HelpURL": null,

This error is being thrown because of a non ascii character in this string Totålly strongly. When attempting to send this over the wire the API is unable to convert the special characters in this string. To solve this issue we simply tell NewtonSoftJson to escape all non-ascii characters.

     centamanJsonSerializerSettings = new JsonSerializerSettings()
       {
        NullValueHandling = NullValueHandling.Ignore,
        StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
       };

How to view Model binding errors

https://stackoverflow.com/questions/28835869/capture-exception-during-request-deserialization-in-webapi-c-sharp?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

  {
      public override void OnActionExecuting(HttpActionContext actionContext)
      {
          if (actionContext.ModelState.IsValid)
          {
              base.OnActionExecuting(actionContext);
          }
          else
          {
              var exceptions = new List<Exception>();
  
              foreach (var state in actionContext.ModelState)
              {
                  if (state.Value.Errors.Count != 0)
                  {
                      exceptions.AddRange(state.Value.Errors.Select(error => error.Exception));
                  }
              }
  
              if (exceptions.Count > 0)
                  throw new AggregateException(exceptions);
          }
      }
  }
  


Samuel Nimako-Mensah

Read more posts by this author.