【问题标题】:Returning an array as a string with Web Api 2 [closed]使用Web Api 2将数组作为字符串返回[关闭]
【发布时间】:2015-06-12 15:40:08
【问题描述】:

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

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

我希望 json 数组作为数组字符串返回。为了实现这一点,我需要如何设置我的响应?我目前使用这种方法设置数组和响应

// 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);

需要以字符串格式返回的数组的目的是我可以将其附加到 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"]"

【问题讨论】:

标签: c# .net asp.net-web-api asp.net-web-api2


【解决方案1】:

如果您在 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(",");

【讨论】:

    【解决方案2】:

    只需将图像映射到字符串数组并从控制器返回该对象。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      相关资源
      最近更新 更多