我正在建设我的第一个网站,却知之甚少。我想从我的服务器上得到一个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中正确地获取它?
我希望我没有包括任何排字。我已经把代码缩减到必要的部分了。如果我发现任何错误,我会编辑这个问题。
发布于 2018-06-08 16:48:11
将.AddWebApiConventions()添加到Startup类中,以注册一个识别返回HttpResponseMessage的操作的输出格式化程序。
或者将操作更改为返回ActionResults。
发布于 2018-06-08 17:00:32
您不需要从您的HttpResponseMessage操作返回Controller。这将导致MVC序列化HttpResponseMessage,而不是实际使用它作为响应消息。您只需要返回您希望MVC使用内容协商处理的对象类型。内容协商是MVC如何解决如何序列化响应对象并将其转换为HTML响应。对于ViewResult来说,这意味着渲染东西(通常是Razor视图)。对于JsonResult,这意味着将返回的对象转换为JSON,然后以JSON作为主体返回一个OK响应。对于POCOs来说,这通常意味着行为就像一个JsonResult。试试这个:
public ActionResult GetPlayers()
{
return Json(“test”);
}或
public string GetPlayers()
{
return “test”;
}发布于 2021-05-04 16:00:53
我使用这个库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);https://stackoverflow.com/questions/50764837
复制相似问题