ASP.NET Core API发送包含在双引号

时间:2017-12-28 15:14:06

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

我的ASP.NET Core API为要上传到Azure Blob存储的文件生成SAS。看起来字符串用双引号括起来,这就是我用来上传文件的前端解决方案的问题。

如何返回一个字符串,但要确保它没有用双引号括起来?

这是API控制器:

public async Task<IActionResult> GetSAS(string blobUri, string _method)
{
    if (string.IsNullOrEmpty(blobUri) || string.IsNullOrEmpty(_method))
       return new StatusCodeResult(400);

    // Get SAS
    var sas = _fileServices.GetSAS(blobUri, _method);

    return Ok(sas);
}

2 个答案:

答案 0 :(得分:5)

正如评论中所讨论的那样,您在强制JSON响应的类上有[Produces]属性。从docs on ProducesAttribute我们可以看到它可以应用于动作以及控制器。因此,您可以通过在其中添加特定操作来覆盖特定操作,在您需要的情况下,您需要text/plain

[Produces("text/plain")]
public async Task<IActionResult> GetSAS(string blobUri, string _method)
{
    //snip
}

答案 1 :(得分:3)

您将返回OkResult,它将序列化传递给它的对象。由于该对象是一个字符串,并且由于默认的序列化程序是JSON,因此您的响应最终为 JSON字符串,即在其周围加上双引号。

要解决此问题,您可以采用多种不同的路径。首先,您只需将返回类型更改为string即可。这将导致ContentResult缠绕它,这不会导致序列化。例如:

public async Task<string> GetSAS(string blobUri, string _method)
{
    ...

    return sas;
}

其次,您可以使用Produces属性将返回内容类型指定为text/plain

[Produces("text/plain")]
public async Task<IActionResult> GetSAS(string blobUri, string _method)

最后,您可以简单地将其保留原样,而是在客户端将结果正确地解释为JSON。您可以在JavaScript代码中使用JSON.parse来获取字符串值:

var sas = JSON.parse(result);