Search code examples
c#asp.net-web-apiasp.net-web-api2

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


While I could use C# to replace the [\ and ] I do not know why they are even appearing.

I Call a Web API service from within a C# application

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\"]"

Why does it have the brackets and backslash?

The Web Api that I call looks like this

[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);
}

Solution

  • I'm guessing you're looking at it in the debugger. The debugger is escaping the quotes, so the string really looks like:

    ["SPRUCEK"]
    

    which makes sense. You're returning an IEnumerable<string>, which in JSON will be an array. You're getting one result back, so the JSON looks on point for what you're returning.

    Judging from your method name, I bet you only want one result. If that's the case, try:

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