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