SendAsync()返回422无法处理的实体

时间:2019-12-09 03:05:06

标签: c# dotnet-httpclient sendasync

我使用 Get Async()编写了一个函数,该函数运行良好,但现在我想使用 Send Async()代替[用于POST和第四]但是我的SendAsync()版本无法按预期运行,它返回422无法处理的实体。 (没有IDE自动取款机;对于小错别字表示抱歉)

init

var Client = new HttpClient{
    BaseAddress = "https://example.com"
}
Client.DefaultRequestHeaders.UserAgent.ParseAdd("Project/1.0 (blah blah)");

...

工作获取异步()

public async Task<string> GetResponse(string user, string pass){
    var uri = $"/user/login.json?name={user}&password={pass}";
    var req = await Client.GetAsync(uri);
    return req.Content.Request.Content.ReasStringAsync();
}

无效的发送异步()

public async Task<string> GetResponse(string page, Dictionary<string, string> args){
//assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
try{
    var req = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri(page),
        Content = new FormUrlEncodedContent(args),
    }

    var response = await Client.SendAsync(req);
    if(response.IsSuccessStatusCode){
        return await response.Content.ReasStringAsync();
    return null;
}
catch{ return null }
}

注意:与422一起,响应仍然包含json,其中指出“无效的Auth令牌!”

GetAsync()在执行SendAsync()不是吗?

2 个答案:

答案 0 :(得分:1)

您的发送在HTTP GET请求的正文中包含内容。

HTTP GET请求不应具有BODY,并且某些服务器将无法处理此类请求。

将字典转换为QueryString并将其包含在URI中。

public async Task<string> GetResponse(string page, Dictionary<string, string> args) {
    //assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
    try {
        QueryString queryString = QueryString.Create(args);
        var uri = new Uri(page + queryString.ToString());
        var request = new HttpRequestMessage(HttpMethod.Get, uri);
        var response = await Client.SendAsync(request);
        if(response.IsSuccessStatusCode){
            return await response.Content.ReadAsStringAsync();
        return string.Empty;
    } catch { return string.Empty; }
}

答案 1 :(得分:0)

您的代码段没有显示它,但是您确定第二个查询的URL已显示

$"/user/login.json?name={user}&password={pass}"

不是

$"/user/login.json"