IHttpActionResult returns 结果带有方括号和转义斜杠,为什么会这样

IHttpActionResult returns result with brackets and escape slash , why is this happening

虽然 我可以使用 C# 来替换 [\ 和 ] 我什至不知道它们为什么会出现。

我从 C# 应用程序中调用 Web API 服务

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:11974/");  
    client.DefaultRequestHeaders.Accept.Clear();

    HttpResponseMessage response = await client.GetAsync("/GetNTIDWithEmail/"+ responseModel.ReferredToNTID + "/");

    if (response.IsSuccessStatusCode)
    {
        var x = await response.Content.ReadAsStringAsync();
    }

}

x = "[\"SPRUCEK\"]"

为什么它有括号和反斜杠?

我调用的 Web Api 看起来像这样

[Route("GetNTIDWithEmail/{id}")]
public IHttpActionResult GetNtidfromEmail(string id)
{
    var query = (from c in _db.rEmails
                    where c.Email.Contains(id)
                select c.ALIAS_NAME);


    return Ok(query);
}

我猜您正在调试器中查看它。调试器正在转义引号,所以字符串看起来像:

["SPRUCEK"]

这是有道理的。您将返回一个 IEnumerable<string>,在 JSON 中将是一个数组。您将返回一个结果,因此 JSON 会查找您返回的内容。

从你的方法名称来看,我敢打赌你只想要一个结果。如果是这样,请尝试:

 var result = (from c in _db.rEmails
                where c.Email.Contains(id)
            select c.ALIAS_NAME)
             .FirstOrDefault();