Search code examples
javascriptc#restgetfetch

fetch string value from C# server


I'm building my first website and know emberassingly little. I want to get a list of players in form of a csv string for a game from my server. In my C# server code I have

[HttpGet("[action]")]
public HttpResponseMessage GetPlayers()
{
    // string csv = String.Join(",", PLAYERS_DB.Keys);
    string csv = "test";
    // I plan to replace "test" with a csv later. For this problem,
    // it's probably enough to handle this test string.
    var resp = new HttpResponseMessage(HttpStatusCode.Accepted);
    resp.Content = new StringContent(csv, System.Text.Encoding.UTF8, "text/plain");
    return resp;
}

I call this in javascript via

callApiGET() {
    return fetch("api/Test/GetPlayers", {
        method: "GET"
    }).then(
        response => response.text()
        // Here I hava also tried to work with response.json()
        // Reading the statusCode from json works flawlessly
    ).then(
        text => {
            console.log(text)
        }
    )
        .catch(error => {
            console.error(error)
            alert(error)
        });
}

(Yes, my class is called TestController.) The console then says:

{
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [{
      "key": "Content-Type",
      "value": ["text/plain; charset=utf-8"]
    }]
  },
  "statusCode": 202,
  "reasonPhrase": "Accepted",
  "headers": [],
  "requestMessage": null,
  "isSuccessStatusCode": true
}    

I expect the important part of the above to be

"content":{"headers":[{"key":"Content-Type","value":["text/plain; charset=utf-8"]}]}

Here I would expect to read "test" somewhere, but I can't. So here is my question:

TL;DR: If my server returns a HttpResponseMessage, how do I send a string together with it, and how do I fetch it properly in Javascript?

I hope that I didn't include any typos. I've cut down my code to the necessary parts. If I find any mistakes, I'll edit the question.


Solution

  • Add .AddWebApiConventions() to your Startup class to register an output formatter that recognizes actions that return HttpResponseMessage.

    Or change your actions to return ActionResults instead.