4

I need help changing the encoding of the response header on .Net Core 1.1.

We're developing an application and we created a custom header called "X-Application-Error" where any error that happens at the backend of the aplication returns a response code 500 and inside the header the message. This way I use the "app.UseExceptionHandler" to catch the errors, put it inside the header, and the front end, if it recieves and response code 500, displays the message sent at the header.

This is working as expected, the trouble that I'm having is that I need to send chacters like "é", "ã" and others, and the default encoding of the header is UTF-8, so it doesn't display those characters.

At the .net framework, we can use the "HttpResponse.HeaderEncoding" Property to change it (https://msdn.microsoft.com/en-us/library/system.web.httpresponse.headerencoding(v=vs.110).aspx) but I can't find the equivalent for the .Net Core (1.1)

I found a similar question here (C# WebClient non-english request header value encoding) but no answer too.

1
  • 1
    Those characters are in the UTF-8 code table. Commented Nov 29, 2017 at 19:44

1 Answer 1

1

Ok, I have found a work around (and yes, it seems obvious to me now).

From what I understood .Net Core won't allow characters like "á", "ã" inside a header if they are not encoded. So I just used "WebUtility.UrlEncode(string)" and sent the message encoded. At the FrontEnd, Angular decoded the message automatically. The code is like:

app.UseExceptionHandler(
          builder =>
          {
              builder.Run(
                async context =>
                {
 //Some validations I make

                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        try
                        {
                            context.Response.Headers.Add("Application-Error", WebUtility.UrlEncode(error.Error.Message));
                        }catch(Exception e)
                        {
                            context.Response.Headers.Add("Application-Error", e.Message);
                        }

                        //the rest of the code
                    }
                });
          });
Sign up to request clarification or add additional context in comments.

Comments

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.