I Am trying to authenticate URL credentials but I am getting this error as:
Task does not contain a definition for 'GetAwaiter'
public class Methods
{
public static async Task<JObject> Get(string url, string username, string password)
{
var credentials = new NetworkCredential(username, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
// client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
return new JObject { response.StatusCode };
}
}
public async Task<IActionResult> Index()
{
// Methods RestMethod = new Methods();
var httpClient = new HttpClient();
var data = await Methods.Get("http://www.myportal.com/api/now/table/core_company", "user#myportal.com", "Password123");
return View();
}
Related
I have an API secured by a bearer token. The API has two controllers, one is the default WeatherForecast and the second one is for handling CRUD operations for player model. I decided to get my token from WeatherForecast and use it to call player in my MVC project.
But when I start debugging, it shows Unauthorized for response in every MVC action. It's ok on using postman though.
Here are the controller methods for HttpGet and HttpPost:
namespace MyMVCProject.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpClientFactory _clientFactory;
public HomeController(ILogger<HomeController> logger, IHttpClientFactory clientFactory)
{
_logger = logger;
_clientFactory = clientFactory;
}
public async Task<IActionResult> Index()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/weatherforecast/");
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string token = await response.Content.ReadAsStringAsync();
HttpContext.Session.SetString("JwtToken", token);
}
return View();
}
public async Task<IActionResult> GetAllPlayers()
{
var accessToken = HttpContext.Session.GetString("JwtToken");
List<Player> players = new List<Player>();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/api/player");
var client = _clientFactory.CreateClient();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var apiString = await response.Content.ReadAsStringAsync();
players = JsonConvert.DeserializeObject<List<Player>>(apiString);
}
return View(players);
}
[HttpPost]
public async Task<IActionResult> AddPlayer(Player player)
{
var accessToken = HttpContext.Session.GetString("JwtToken");
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/player/");
if (player != null)
{
request.Content = new StringContent(JsonConvert.SerializeObject(player), System.Text.Encoding.UTF8, "application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
else
{
return BadRequest();
}
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
var apiString = await response.Content.ReadAsStringAsync();
player = JsonConvert.DeserializeObject<Player>(apiString);
TempData["success"] = "Player Added Successfully!";
}
else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
TempData["badrequest"] = "Player with the same name already exists";
}
return View(player);
}
}
}
HttpRequestMessage has a Headers property of type HttpRequestHeaders. This class has two Add methods you can use.
You can add headers like this:
request.Headers.Add("Authorization", "Bearer " + YourToken);
I am using this syntax
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
This is my method
static public async Task<string> Get(string token, string url)
{
HttpClient httpclient = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
{
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
request.Headers.Host = "api.ws.sonos.com";
var response = await httpclient.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
and this is how I call it in my main
namespace ApiTest
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine(ApiConnect.Get("My Access Token", "https://api.ws.sonos.com/control/api/v3/households").Result);
I'm try to get the list of households registered to my account but I get a 404 error.
You are not sending your client key or setting the content type to json.
I call this WebApi endpoint:
public IActionResult MyEndPoint([FromBody] MyType myType)
{
// I do some stuff
var answer = new MyAnswer { Id = Guid.NewGuid() };
return Ok(answer);
}
The call to call the endpoint is this:
public async Task<string> httpPost(string url, string content)
{
var response = string.Empty;
using(var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
HttpResponseMessage result = await client.SendAsync(request);
if(result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString(); //here
}
}
return response;
}
I'd like to have access MyAnswer object returned with the Ok() where the //here is. I put a breakpoint but nothing look like my object.
public async Task<MyAnswer> HttpPost(string url, string content)
{
var response = new MyAnswer();
using (var client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json")
};
HttpResponseMessage result = await client.SendAsync(request);
if (result.IsSuccessStatusCode)
{
var responseString = await result.Content.ReadAsStringAsync();
response = JsonSerializer.Deserialize<MyAnswer>(responseString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
}
return response;
}
I have a httpclient that is calling a WebAPI service. The GET reaches the service and returns the content but the client just keeps waiting...
Client code:
static async Task RunAsyncGet(string baseUri, string uri)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage response = await client.GetAsync(uri); // <-- stuck here
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
IEnumerable<UserAccountModel> users = await response.Content.ReadAsAsync<IEnumerable<UserAccountModel>>();
//...
}
}
}
WebAPI code:
public class UserAccountController : ApiController
{
private IRepository _repo;
public UserAccountController(IRepository repo)
{
_repo = repo;
}
public HttpResponseMessage Get()
{
var s = _repo.GetAllUserAccounts();
IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(typeof(AuthResponseModel), Request, Configuration.Formatters);
var bestMatchFormatter = result.Formatter;
var mediaType = result.MediaType.MediaType;
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent<IQueryable<UserAccount>>(s, bestMatchFormatter, mediaType)
};
}
}
Thoughts?
Further up in your client code (whatever ends up calling RunAsyncGet), some code is calling Task.Wait or Task<T>.Result. That will cause a deadlock if called from the UI thread, as I explain on my blog.
The proper solution is to change that Wait/Result to use await.
This is how I ended up calling the WebAPI:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:23302");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/useraccount").Result;
if (response.IsSuccessStatusCode)
{
var t = response.Content.ReadAsAsync<IEnumerable<UserAccount>>().Result;
...
}
else
{
//Something has gone wrong, handle it here
}
}
It seems that your call to EnsureSuccessStatusCode is the likely culprit. That method actually returns a HttpResponseMessage that will have a HTTP status in the 200 range, or will throw an exception. So, you probably want something like:
static async Task RunAsyncGet(string baseUri, string uri)
{
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage response = await client.GetAsync(uri);
IEnumerable<UserAccountModel> users = await response.EnsureSuccessStatusCode().Content.ReadAsAsync<IEnumerable<UserAccountModel>>();
// ... the rest ...
}
I have webapi and her method:
[HttpPost, HttpGet]
[ActionName("GetData")]
public MyData GetData([FromUri] MyData data)
{
return datamanager.get(data);
}
How do I invoke this method? I.e. how do I send data parameter through query part of URL?
To invoke get method which takes no parameters I use following code:
public static async Task<myClassl> GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://sasa.com");
HttpResponseMessage response = await client.GetAsync("api/GetData");
myClassl data = await response.Content.ReadAsAsync<myClassl>();
return data ;
}
Thanks.
Try the following solution:
HttpClient client = new HttpClient();
string baseApiAddress = ConfigurationManager.AppSettings["baseApiAddress"];
client.BaseAddress = new Uri(baseApiAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response=client.GetAsync("/api/GetData",data, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{
var mydata = response.Content.ReadAsAsync<MyData>().Result;
}
else
{
Debug.WriteLine(response.ReasonPhrase);
}