1

I have payload in a HTTP POST body where I need to apply HTML decoding on specific fields before forwarding to the backend. How can I achieve this in API Management policy expressions where System.Web.HttpUtility.HtmlDecode seems not to be available - also see feedback forum?

Trying to use a self-made version fails, because policy editor translates ä to ä:

<set-body>@{ string HtmlDecode(string input) => input.Replace("&auml;","ä"); var body = context.Request.Body.As<JObject>(true); body["field1"] = HtmlDecode(body["field1"].ToString()); return body.ToString(); }</set-body> 
4
  • Do you have access to the System.Net.WebUtility namespace? stackoverflow.com/questions/35437491/… Commented Oct 2, 2018 at 15:40
  • unfortunately no, when trying a System.Net.WebUtility.HtmlDecode() I get: Usage of type 'System.Net.WebUtility' is not supported within expressions Commented Oct 2, 2018 at 15:48
  • This functionality looks to be missing indeed. You could try escaping the ampersand .Replace("\u0026auml;","ä") but you are going to have to do a lot of find/replace. Commented Oct 2, 2018 at 18:28
  • Thanks @dana, I'll try this as a workaround until a final solution comes into place Commented Oct 2, 2018 at 20:19

3 Answers 3

4

not my preferred and intended solution but with help of @Dana and Maxim Kim (API Management team) a workaround:

<set-body>@{ Dictionary<string,string> decoderPairs = new Dictionary<string,string>() { {"&amp;auml;","ä"}, {"&amp;ouml;","ö"}, {"&amp;uuml;","ü"}, {"&amp;Auml;","Ä"}, {"&amp;Ouml;","Ö"}, {"&amp;Uuml;","Ü"}, {"&amp;szlig;","ß"}, {"&amp;amp;","&"} }; string HtmlDecode(string input) { foreach(var p in decoderPairs) { input = input.Replace(p.Key,p.Value); } return input; } var body = context.Request.Body.As<JObject>(true); body["field1"] = HtmlDecode((body["field1"] ?? "").ToString()); return body.ToString(); }</set-body> 

EDIT

since this release the proper solution is available

<set-body>@{ var body = context.Request.Body.As<JObject>(true); body["field1"] = System.Net.WebUtility.HtmlDecode((body["field1"] ?? "").ToString()); return body.ToString(); }</set-body> 
Sign up to request clarification or add additional context in comments.

Comments

1

Now you don't even have to use c# to decode your HTML escaped string. Just use the System.Net.WebUtility.HtmlDecode directly:

<set-body>@(System.Net.WebUtility.HtmlDecode(escaped_string))</set-body> 

Comments

0

Since API Management policy expressions support XDocument, you can use this to decode most blocks of html/xml data:

string DecodeHtml(string value) { if (value == null) return null; return XDocument.Parse($"<root>{value}</root>").Root.Value; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.