Reputation: 4031
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("ä","ä");
var body = context.Request.Body.As<JObject>(true);
body["field1"] = HtmlDecode(body["field1"].ToString());
return body.ToString();
}</set-body>
Upvotes: 1
Views: 2177
Reputation: 227
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>
Upvotes: 1
Reputation: 4031
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>()
{
{"&auml;","ä"},
{"&ouml;","ö"},
{"&uuml;","ü"},
{"&Auml;","Ä"},
{"&Ouml;","Ö"},
{"&Uuml;","Ü"},
{"&szlig;","ß"},
{"&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>
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>
Upvotes: 4
Reputation: 71
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; }
Upvotes: 0