简体   繁体   中英

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>

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>

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>

由于 API 管理策略表达式支持 XDocument,您可以使用它来解码大多数 html/xml 数据块:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM