以前我在单个类中处理了所有的http请求,但我想将http登录功能移到另一个类但现在我无法访问http客户端response.IsSuccessStatusCode
这是我的原始代码
var http = new HttpClient();
var url = String.Format(shared.AppDetails.domainurl+"/v2auth/default/login");
var response2 = await http.PostAsync(url, credentials);
if (response.IsSuccessStatusCode)
{
//do after login stuff
}
现在我想将登录逻辑移动到另一个不同文件夹中的类(auth-> dbhelpers)
class LoginHttp
{
public static async Task<object> loginAsync(String username, String password)
{
var values = new Dictionary<string, string>
{
{ "username",username },
{ "password", password }
};
var credentials = new FormUrlEncodedContent(values);
var http = new HttpClient();
var url = String.Format(shared.AppDetails.domainurl + "/v2auth/default/login");
var response = await http.PostAsync(url, credentials);
return response;
}
}
现在正尝试通过
访问返回的响应var responsefromhttplogin = auth.dbhelpers.AuthHttp.loginAsync(login_username.Text, login_password.Password);
if (responsefromhttplogin .IsSuccessStatusCode) //this fails
{
//do after login stuff
}
如何再次获得HttpClient类型的后续响应? 我的错误是
Task<Objct> does not contain defination for IsSuccessStatusCode
答案 0 :(得分:0)
尝试将代码更改为等待异步方法,如下所示:
tests
现在添加等待后,var responsefromhttplogin = await auth.dbhelpers.AuthHttp.loginAsync(login_username.Text, login_password.Password);
if (responsefromhttplogin.IsSuccessStatusCode)
{
//do after login stuff
}
应该可以访问。
并且还要更改您的方法以返回responsefromhttplogin.IsSuccessStatusCode
而不是Task<HttpResponseMessage>
答案 1 :(得分:0)
您将从SELECT opreator.o_name, c1.c_name as dept, c2.c_name as destination, route.fare
FROM route
JOIN opreator ON route.opreator = opreator.id
JOIN city c1 ON route.dep = c1.id
JOIN city c2 ON route.dest = c2.id
返回Task<object>
,以访问您可以使用loginAsync()
任务的结果。
我会考虑缩小您从Task.Result
返回object
的类型。
答案 2 :(得分:0)
使您的loginAsync方法返回Task。目前您正在返回一个对象,然后您将可以访问IsSuccessStatusCode
YourClass result = mapper.reader(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.forType(YourClass.class)
.readValue(json);
}
您还需要在调用方法中使用await,否则您将获得一个任务
class LoginHttp{
public static async Task<HttpResponseMessage> loginAsync(String username, String password)
{
var values = new Dictionary<string, string>
{
{ "username",username },
{ "password", password }
};
var credentials = new FormUrlEncodedContent(values);
var http = new HttpClient();
var url = String.Format(shared.AppDetails.domainurl + "/v2auth/default/login");
var response = await http.PostAsync(url, credentials);
return response;
}
答案 3 :(得分:0)
根据您的代码判断,您将返回Task<object>
您应该将return response;
转换为return (HttpResponseMessage) response;
或将返回类型更改为Task<HttpResponseMessage>