我正在忙着开发一个Xamarin表单应用程序,并且在过去的两天里一直在努力从应用程序中成功发布我的webApi。从Chrome Postman应用程序发布到WebApi可以很好地工作,但我似乎无法从应用程序中获取它。
这是我试图调用的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 Express,但在帖子上读到使用外部设备时无法完成此操作,因此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。
任何人都可以对此有所了解吗?
答案 0 :(得分:0)
我认为这里的问题是你试图击中的Uri。由于Url不正确,SendAsync方法可能会抛出404。
请更改以下行:
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "User/Authenticate"))
到
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "api/User/Authenticate"))
假设您的BaseAddress以&#39; /&#39;结尾最后,否则它将是
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "/api/User/Authenticate"))