2

缓存的响应返回所有引号已转义并添加了 \n 字符。结果字符串也用引号括起来。不缓存时,html 会很好地返回。我该如何度过这个难关?我在客户端使用 angularjs 发出 API 请求并将返回值设置为 div 的 $.html()。

if (enableCaching)
{
    var cacheKey = UrnId.Create<ContentValueRequest>(Request.Group, Request.Key);
    var expireInTimespan = new TimeSpan(0, 5, 0);

    return base.RequestContext.ToOptimizedResultUsingCache(base.Cache, cacheKey, expireInTimespan, () => {
        return GetContentValueRequest(Request);
    });
}
else
    return GetContentValueRequest(Request);
4

1 回答 1

1

不确定我是否有所有的上下文/代码来回答这个问题,但下面的代码似乎对我有用。如果?formt=html未包含在 ServiceStack 请求 url 中,它将返回一个 JSON 字符串,引号被转义并添加 \n 字符。

html

<div ng-app="testApp">

    <div ng-controller="testCtrl">

        <p>Write Contents Below:</p>

        <div id="writeHere"></div>
    </div>

</div>

角码

angular.module('testApp', [], function () {

})
.controller('testCtrl', function ($scope, $http) {

    var req = $http.get('/api/CacheTest?format=html');
    req.success(function (data) {
        $('#writeHere').html(data);
    });
    req.error(function (data) {
        $('#writeHere').html('Error');
    });

});

请求与服务

[Route("/CacheTest")]
public class ContentValueRequest
{
    public string Group { get; set; }
    public string Key { get; set; }
}

public class CacheService : Service
{
    public object Get(ContentValueRequest Request)
    {
        var enableCaching = true;
        if (enableCaching)
        {
            var cacheKey = UrnId.Create<ContentValueRequest>("someKey");
            var expireInTimespan = new TimeSpan(0, 5, 0);

            return base.RequestContext.ToOptimizedResultUsingCache(base.Cache, cacheKey, expireInTimespan, () =>
            {
                return GetContentValueRequest(Request);
            });
        }
        else
            return GetContentValueRequest(Request);
    }

    private string GetContentValueRequest(ContentValueRequest request)
    {
        var ret = @"<em>""Quoted Text"", <em>Bold</em>" + Environment.NewLine;
        ret += @"A second line.";
        return ret;
    }
}
于 2013-10-04T05:02:36.057 回答