0
我正在忙于开发一个Xamarin表单应用程序,并且一直在挣扎过去的两天才从应用程序中获得一个成功的帖子给我的webApi。从Chrome Postman应用程序发布到WebApi完美,但我似乎无法从应用程序中获取它。在Xamarin中使用HttpClient的SendAsync表单不等待
这是我想调用的WebAPI方法:
[HttpPost]
public string Authenticate(HttpRequestMessage request)
{
string JsonObj = request.Content.ReadAsStringAsync().Result;
AuthToken _authToken = JsonConvert.DeserializeObject<AuthToken>(JsonObj);
int UserID = DomainAuth.ValidateDomainAccount(_authToken.Username, _authToken.Password);
if(UserID > 0)
{
_authToken.UserID = UserID;
_authToken.Authenticated = true;
}
else
{
switch(UserID)
{
case -99:
_authToken.AuthMessage = "The entered domain account does not exist";
break;
case -98:
_authToken.AuthMessage = "The entered domain account does not have application access";
break;
case -97:
_authToken.AuthMessage = "Incorrect username and password combination";
break;
}
}
return JsonConvert.SerializeObject(_authToken);
}
我原本是想发布到IIS表达,但在后,采用这样的API外部设备时,这不能做阅读现在在IIS中托管。
这是方法,我的ViewModel命令拨打电话:
public async void Login()
{
Tuple<bool, string> AuthCheck = await _authService.AuthenticateDomainAccount(_username, _password);
if (AuthCheck.Item1) //Item1: True/False value indicating if the login was a success
{
Helpers.Settings.Username = _username;
await _navigationService.NavigateAsync("Synchronization");
}
else
{
FeedbackMsg = AuthCheck.Item2; // Item2: Message indicating why the login has failed.
}
}
而且最后这是使API调用的方法:
public async Task<Tuple<bool, string>> AuthenticateDomainAccount(string _Username, string _Password)
{
AuthToken _authToken = new AuthToken { Username = _Username, Password = _Password };
HttpClientHandler handler = new HttpClientHandler();
using (var client = new HttpClient(handler, false))
{
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "User/Authenticate"))
{
req.Content = new StringContent(JsonConvert.SerializeObject(_authToken), Encoding.UTF8, "application/json");
try
{
var response = await client.SendAsync(req);
Debug.WriteLine("@@@@@@@@@@@@@@@@@ HERE I AM @@@@@@@@@@@@@@@@");
var result = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
string a = "a";
}
}
}
return null;
}
当我通过应用程序步骤它击中SendAsync行,但不是等待它按预期返回,而是跳过它下面的行,并立即根据方法的最后一行返回null。
任何人都可以对此有所了解吗?
你能检查WebAPI是否收到您的Xamarin应用程序的任何请求? – larsbe
在例外区域内打印'Debug.WriteLine(“调用SendAsync的异常:”+ ex.ToString());' – samgak