[英]Cant get Authorized with my API that has a JWT authentication Im Working With Xamarin
Well Im new in Xamarin
and I'm developing and App, the authentication is JWT
based. 好吧,我是Xamarin
新手,我正在开发App,身份验证是基于JWT
的。 Im using a HttpClient
and setting the AuthenticationHeaders
but It always returns Unauthorized
when I try it on Postman
it Works but I can't make it work in my app. 我正在使用HttpClient
并设置AuthenticationHeaders
但是在Postman
上尝试运行时它总是返回Unauthorized
,但是我无法在我的应用程序中使其正常工作。
Here is how im trying to do it: 这是即时通讯尝试执行的操作:
var client = new HttpClient(new HttpClientHandler());
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("JWT", accessToken);
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
Try something like this 试试这个
using (var client = new HttpClient())
{
var uri = new Uri(string.Format($"{<yourURLString>}", string.Empty));
var jsonTransport = "";
var jsonPayload = new StringContent(jsonTransport, Encoding.UTF8, "application/json");
//client.DefaultRequestHeaders.Add("Content-type", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var response = await client.PostAsync(uri, jsonPayload);
string responseContent = await response.Content.ReadAsStringAsync();
}
then deserialize the responseContent to your object using JsonConvert.DeserializeObject Note: Below are code samples, edit to your own objects 然后使用JsonConvert.DeserializeObject将responseContent反序列化到您的对象注意:以下是代码示例,请编辑到您自己的对象
SubscriptionResponse profileResponse = JsonConvert.DeserializeObject<SubscriptionResponse>(responseContent);
then if your method returns something, use the return statement. 然后,如果您的方法返回了某些内容,请使用return语句。 Something like this 像这样
return profileResponse.Data.Subscriptions;
If you're using a get, this could be a guide 如果您使用的是get,这可能是一个指南
var uri = new Uri(string.Format($"{<yourURLHere>}", string.Empty));
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var httpResponse = await client.GetAsync(uri);
var responseContent = await httpResponse.Content.ReadAsStringAsync();
then deserialize your string response Note: this is a sample - edit to your model (You may use PostMan to get the response format in JSON and model it in C#) 然后反序列化您的字符串响应注意:这是一个示例-编辑模型(您可以使用PostMan获取JSON中的响应格式并在C#中对其进行建模)
var UserDetailResponse = JsonConvert.DeserializeObject<UserDetail>(responseContent);
return UserDetailResponse;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.