使用 Web Api 2 将数组作为字符串返回

Returning an array as a string with Web Api 2

我有一个 Web Api 2 端点,returns Json 包含一组图像 url。它的响应看起来像这样

   {
    "Status": 0,
    "Message": "Success",
    "Images": [
        "http://some.image.com/somepath/SomeReport-0.png",
        "http://some.image.com/somepath/SomeReport-1.png"
    ]
   }

我希望json 数组到return 作为数组字符串。我需要如何设置我的响应才能实现该目标?我目前使用此方法设置数组和响应

// response.status and response.message are added before this

response.Images = imagePaths.Select(x => string.Format(urlString, Path.GetFileName(x)));

HttpResponseMessage apiResponse = Request.CreateResponse(HttpStatusCode.OK, response);

需要数组 return 字符串格式的目的是这样我可以将它附加到 html 数据属性。现在,如果我像这样引用响应:

listItem.append('<a class="dd-option" data-path="' + response.Images + '" href="#"></a>');

属性里面的内容看起来像

data-attr="http://some.url.com/somepath/ReportStore/image-0.png,http://some.url.com/somepath/ReportStore/image-1.png"

而不是

data-attr="["http://some.url.com/somepath/ReportStore/image-0.png","http://some.url.com/somepath/ReportStore/image-1.png"]"

只需将图像映射到字符串数组,然后 return 来自控制器的对象。

public string[] Get()
{
     //create this array object from your images object
     return new string[]{"imagePath1", "imagePath2", "imagePath3"};
}

如果您在 javascript 中执行此操作,那么您可以 JSON.stringify

var jsonResponse = 
    {
    "Status": 0,
    "Message": "Success",
    "Images": [
        "http://some.image.com/somepath/SomeReport-0.png",
        "http://some.image.com/somepath/SomeReport-1.png"
    ]
   }

 var images = JSON.stringify(jsonResponse.Images);

console.log(images);

$("#foo").append($("<li>").text("foo").attr("data-foo", images));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="foo">
</ul>

这会给你

<li data-foo="["http://some.image.com/somepath/SomeReport-0.png","http://some.image.com/somepath/SomeReport-1.png"]">foo</li>

但您需要注意引号,因为它可能会生成无效的 html。

然而,即使你有

data-attr="http://some.url.com/somepath/ReportStore/image-0.png,http://some.url.com/somepath/ReportStore/image-1.png"

你可以在服务器端使用 String.join() 然后你可以使用 javascript split() 来再次获取数组。

var imagesArr = ($(this).data("attr")).split(",");