Kai Walter
Kai Walter

Reputation: 4031

How can I apply HTML decoding in an Azure API Management (C#) policy expression?

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>

Upvotes: 1

Views: 2177

Answers (3)

K.J.M.O.
K.J.M.O.

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

Kai Walter
Kai Walter

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>() 
    {
        {"&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>

Upvotes: 4

smokedlinq
smokedlinq

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

Related Questions