从C#server

时间:2018-06-08 16:24:42

标签: javascript c# rest get fetch

我正在建立我的第一个网站并且知道很少。我想从我的服务器获取一个csv字符串形式的玩家列表。在我的C#服务器代码中我有

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

我在javascript中通过

调用此方法
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)
        });
}

(是的,我的班叫做TestController。) 然后控制台说:

{
  "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
}    

我希望上面的重要部分是

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

在这里,我希望在某处阅读“测试”,但我不能。所以这是我的问题:

TL; DR :如果我的服务器返回HttpResponseMessage,如何将字符串与其一起发送,以及如何在Javascript中正确获取它?

我希望我没有包含任何拼写错误。我已将代码减少到必要的部分。如果我发现任何错误,我会编辑问题。

5 个答案:

答案 0 :(得分:2)

.AddWebApiConventions()添加到Startup类以注册输出格式化程序,以识别返回HttpResponseMessage的操作。

或者更改您的操作以返回ActionResult

答案 1 :(得分:0)

您无需从HttpResponseMessage操作中返回Controller。这将导致MVC序列化HttpResponseMessage,而不是实际使用它作为响应消息。您只需要使用内容协商返回您希望MVC处理的对象类型。内容协商是MVC如何计算响应对象的序列化并将其转换为HTML响应的方式。对于ViewResult s,这意味着渲染内容(通常是Razor视图)。对于JsonResult,这意味着将返回的对象转换为JSON,然后返回一个OK响应,并将该JSON作为正文。对于POCO,这通常意味着就像JsonResult一样。试试这个:

public ActionResult GetPlayers()
{
    return Json(“test”);
}

或者

public string GetPlayers()
{
    return “test”;
}

答案 2 :(得分:0)

我使用这个库 https://www.nuget.org/packages/Fetch_dotNET/

// TOKEN JWT
var fetchOptions2 = "{" +
    "'method': 'GET'," +
    "'headers': {" +
        "'Accept': 'application/json'," +
        "'Content-Type': 'application/json'," +
        "'Authorization': 'Bearer " + jwt + "'," +
        "'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0;)'" +
    "}," +
    "'timeout': 3000" + // 3 second timeout
"}";


// method: 'GET WITH TOKEN JWT'
Console.WriteLine("> GET WITH TOKEN JWT");
var httpResponseJWT = await HttpClient.FetchAsync(address, fetchOptions2, data);
Console.WriteLine("response:");
Console.WriteLine(httpResponseJWT);
DisplayResponseStatus(httpResponseJWT);

答案 3 :(得分:-1)

试试这个语法:

$.ajax({
  url: "api/Test/GetPlayers",
  method: "GET"
})
  .done(function( data ) {
      console.log(data);
  });

答案 4 :(得分:-1)

要将原始文本写入输出,您可以直接处理HttpResponse而不是返回值,如下所示:

    [HttpGet("[action]")]
    public void GetRawString()
    {
        string csv = "a,c,d";
        Response.ContentType = "text/plain; charset=UTF-8";
        Response.Body.Write(Encoding.UTF8.GetBytes(csv));
    }