2013-10-01 20 views
2

緩存的響應返回,並且所有引號都已轉義並添加了\ n個字符。結果字符串也用引號括起來。沒有緩存時,html返回就好了。我如何克服這個問題?我在客戶端上使用angularjs來創建API請求,並將返回的值設置爲div的$ .html()。使用.ToOptimizedResultUsingCache()從ServiceStack緩存集返回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); 

回答

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; 
    } 
} 
+0

真棒!我會測試一下,如果它在我的結尾工作,給你信貸。非常感謝。 – joeldow

+0

我想在JSON中返回HTML,它通常與自定義響應對象一起工作,但似乎不適用於單個字符串(html)值。 – joeldow

+0

我認爲這是問題https://github.com/ServiceStack/ServiceStack/wiki/Service-return-types#different-return-types。返回一個字符串(類型)直接寫入響應流,所以沒有序列化發生。 – paaschpa