无法从“字符串”转换为“System.Net.Http.HttpRequestMessage”

Fra*_*cia 1 .net c# asp.net xamarin.android xamarin

我对 c# 和一般的 API 请求很陌生,所以不确定我的代码是否有意义。现在我只是想从我的 API 的 URL 调用中获取数据并将其显示到一个TextView被调用的testText. 无论我能做什么,我都愿意使用RestSharpHttpClient

public class MainActivity : Activity
{

    HttpClient client;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
    }

    public async Task<string> GetResponseString()
    {
        var request = "http://localhost:51843/api/values/getMessage?id=1";
        var response = await client.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的公共async Task<>方法中,我得到了

无法从“字符串”转换为“System.Net.Http.HttpRequestMessage”

request变量的错误。我留下了所有其他尝试的评论,如果我应该尝试其中任何一个,请告诉我

Jas*_*son 5

SendAsync 有一个 HttpRequestMessage 参数,您正在传递一个字符串。这正是错误告诉你的。

如果您查找HttpRequestMessage,它需要一个方法和一个 URI

var url = "http://localhost:51843/api/values/getMessage?id=1";
var req = new HttpRequestMessage(HttpMethod.POST, new Uri(url));
Run Code Online (Sandbox Code Playgroud)