0

I've created an API.NET Web API. It uses the default utf-8 content encoding. I need the output to be in latin-1 to match the database.

8
  • If your output encoding needs to match your database encoding, you're probably doing it wrong... joelonsoftware.com/articles/Unicode.html Commented Jan 30, 2014 at 13:52
  • Can you elaborate as to how I should do it? My DB uses Latin-1 encoding, characters from this DB are then displayed on a webpage which is utf-8 (as default), so I want to set the page to Latin 1 so characters are displayed properly. Commented Jan 30, 2014 at 14:00
  • Are you extracting data from the DB as raw byte-arrays and emitting these directly to your output? If you're using a DB library that handles text types from the DB as .net strings, these should be converted to UCS-2 like all other .net strings by the library, and your database encoding should be irrelevant. Commented Jan 30, 2014 at 15:05
  • Can you give me an example of when it's okay to have utf-8 in the db and a different encoding type on the rendered webpage? Commented Jan 30, 2014 at 15:09
  • 1
    Agreeing with Jonas here. The "output" of the rendering goes to the browser and at that point it gets encoded from .net's Unicode strings to whatever the content negotion resulted in. If a) your data looks good in the database, b) it looks bad on a latin1 browser and c) you are sure that all database characters are actually translatable into latin1, the problem is with your database access. You can check this by looking at the .net strings in the debugger when stepping through your controller actions. If they are garbage, asp.net can't do anything about it. Commented Dec 16, 2016 at 21:18

1 Answer 1

2

There is a article here that shows how to do this http://blogs.msdn.com/b/henrikn/archive/2012/04/22/asp-net-web-api-content-negotiation-and-accept-charset.aspx

You just need to change from this article to remove all the encode suported and include just latin-1

something like this in your app start

   protected void Application_Start()
   {

       Encoding latinEncoding = Encoding.GetEncoding("Latin-1");
       GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedEncodings.Add(latinEncoding);
       GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedEncodings.RemoveAt(0);

   } 

And add the below namespace:

using System.Text;
Sign up to request clarification or add additional context in comments.

1 Comment

JsonFormatter is null and I get a runtime exception trying to add to its supported encodings. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.