How to use HttpClient in ASP.NET Core app - asp.net

I am trying to build an app with ASP.NET Core (aka vNext). I need to call a third-party REST-API. Traditionally, I would use HttpClient. However, I can't seem to get it to work. In my project.json file I have:
"dependencies": {
"Microsoft.Net.Http.Client": "1.0.0-*"
}
When I run dnu restore, I receive an error that says: "Unable to locate Microsoft.Net.Http.Client >= 1.0.0-*". The other post referred to by the commenter is out-of-date.
I am building this app in Mac OS X. I don't think that makes a difference. Still, Is HttpClient the recommended approach for calling a third-party REST API? If not, what should I be using? If it is, what am I doing wrong?
Thank you!

Did you try Microsoft ASP.NET Web API 2.2 Client Library
Just add reference to your project.json file as below:
"dependencies": {
"Microsoft.AspNet.WebApi.Client": "5.2.3"
}
And after package restore, you can call your Web Api like below:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourapidomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
var product = await response.Content.ReadAsAsync<Product>();
}
}
You can also find a detailed tutorial at http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

I'm looking at the NuGet page for that package. The earliest version number is 2.0.20505. Your project specifies anything that's 1.0.0-*. Seems like that would exclude a 2.X version. Try just specifying the latest version 2.2.29.
Note that I'm not 100% familiar with how vNext resolves packages, so 1.0.0.0-* could very well pull in a 2.X package, my answer is just a guess based on the syntax. Let me know if it doesn't work and I'll remove my answer.

Related

Get role of current user in Sharepoint Online site using Microsoft Graph

I am building a .net core web app in which i use AzureAD auth and Microsoft Graph to get data from a sharepoint online site.
I need to get the groups of the current user.
I tried to use graphClient.Me.MemberOf.Request().GetAsync();
I think i'm getting the role of the user in the Azure directory.
But i want the role of the current user for a specific sharepoint online site.
Is that possible to get this information and how ?
I don't find a working way to get this using Microsoft Graph.
EDIT:
As Microsoft Graph doesn't allow to get that data.
I tried to call the following Sharepoint Online API endpoint :
https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups
Using this api endpoint i can see all the roles of the current user in my browser.
But i don't find how to call it from my .net core web app.
Tried the following :
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-types", "application/json;odata=verbose");
var response = await client.GetAsync("https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
}
But that give me a 403 response.
EDIT 2 :
I am currently trying to use CSOM to get this informations(TCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200.)
But i don't find a way to get TokenHelper.cs.
var token = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipalId, webUri.Authority, null).AccessToken;
var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), token);
I tried to add "AppForSharePointOnlineWebToolkit" and it did not add the needed files in the project.
How can i get the TokenHelper.cs file ?
Thanks for any help.
Tristan
To execute CSOM code in .net core, do below settings.
We can install the package as below.
Install-Package TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200 -Version 16.1.8029.1200
More information is here: TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200
Or use the following solution from GitHub: NetCore.CSOM
Or follow the steps below.
1.Create a .NET Core console app.
2.Add the references: Microsoft.SharePoint.Client.Portable.dll, Microsoft.SharePoint.Client.Runtime.Portable.dll, and Microsoft.SharePoint.Client.Runtime.Windows.dll.
Note: If the project has references to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll, please remove them.
These references can be accessed by installing CSOM library into another project, and then navigating to installed nuget packages in the file directory: c:\Users\user.nuget\packages\microsoft.sharepointonline.csom(version)\lib\netcore45
3.Add the code below to the .NET Core 2.0 console application:
Get current user role:
To get the current user role, you can use Web.GetUserEffectivePermissions method.
Ex:
ClientResult<BasePermissions> permission= web.GetUserEffectivePermissions(name);
context.ExecuteQuery();
var res = permission.Value;
Refer below link to get clientcontext using access token: https://www.sharepointpals.com/post/how-to-get-the-client-context-using-app-access-token-by-passing-client-id-and-client-secret-id-using-csom-in-sharepoint-office-365/
No. Microsoft Graph doesn't expose an endpoint that allows you to get the information of SharePoint Group and its members.
If you has this requirement, you could vote this idea on Microsoft Graph UserVoice.

How to setup ElmahCore for a Console Application?

I want to log errors for a console application using Elmah.I've found ElmahCore and elmah.io.core but I don't know how to setup any of them on a console app.I'm using .net core.
ELMAH (the open source project) doesn't work with .NET Core. ElmahCore has a lot of dependencies to ASP.NET Core, but if you really wanted to, you could do something like this:
class Program
{
static void Main(string[] args)
{
var log = new MemoryErrorLog();
log.Log(new Error(new Exception()));
var errors = new List<ErrorLogEntry>();
var result = log.GetErrors(0, 10, errors);
Console.WriteLine(result);
Console.WriteLine(errors);
Console.ReadLine();
}
}
You can replace MemoryErrorLog with a target logger of your choice.
The package named elmah.io.core is a deprecated package from elmah.io. elmah.io is (among other things) a commercial cloud version of ELMAH, where you store all of your errors in the cloud (list of differences between ELMAH and elmah.io). elmah.io works with .NET core through either the Elmah.Io.Client NuGet package or using one of the integrations for popular logging frameworks like Serilog and NLog.
I wouldn't recommend you to use ElmahCore for logging in a console application. It is created for ASP.NET Core. There are much better options for logging from a console application, like the mentioned logging frameworks.

Modelling an existing database in .NET Core 2.x

I have an existing application. I am trying to port some pieces over from .NET 4.x over to .NET Core. I have created a context in my .NET Core app. I have create a db context via scaffold-dbcontext. I can run a basic query (hooray). Life is good. Now, I want to add in some async queries. I get the following error:
System.InvalidOperationException: 'The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068.'
code:
var ctx = new GolfGameContext();
var userId = await (from u in ctx.AspNetUsers where u.Token == UserToken select u.Id).SingleAsync();
return userId;
This error seems strange. I have created some .NET Core 2.x apps from scratch and everything seems to work properly. I am able to do async queries with them just fine. When I look at the error link, I get taken to information about EF 6.x. I am guessing that there is something that the scaffold-dbcontext puts in the resulting models that cause this problem. I am also guessing that the code I have created in Core 2.x doesn't contain these same limitations. Am I on the right track? Do I need to change something in my context/models to get async to work properly? All thoughts are welcome.
TIA,
Wally

How to call a RESTful API with ASP.NET 5

Working with ASP.NET 5 on my Mac in Visual Studio Code. I have a RESTful API I need to call and not sure exactly how to do it. I've seen many examples using WebClient, HttpClient, WebRequest and HttpWebRequest.
I think my pain point is the dnxcore50 framework. Can someone please point me in the right direction with some code samples?
Here is an example about how to call a service. Please check the References and using carefully.
One important thing you have to do is install the Web API Client Libraries package: From the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command: Install-Package Microsoft.AspNet.WebApi.Client.
For the full source code, check this link.
I'm assuming it's the same way we used to do it prior to ASP .NET 5, so first you install the ASP .NET Web API Client Libraries NuGet package.
With that available, you reference System.Net.Http:
using System.Net.Http;
Then you use it as follows:
using (var httpClient = new HttpClient())
{
var response1 = await httpClient.GetAsync(url1);
var response2 = await httpClient.PostAsync(url2);
var response3 = await httpClient.SendAsync(url3);
}
That just gives you the response. Typically you'll want to look into the content, especially for GET requests. You can do this by:
var content = await response1.Content.ReadAsStringAsync();
That merely gives you the string in the content, so if it's JSON, you probably want to use something like JSON.NET (Newtonsoft.Json) to deserialize it into structured classes.
This is from memory so you might need a little tweak here and there.
To do this I'm using the NuGet feed https://api.nuget.org/v3/index.json
In my project.json I currently have these relevant dependencies and just use the "dnxcore50" framework:
"Microsoft.AspNet.WebApi.Client": "5.2.3",
"System.Net.Http": "4.0.0",
"System.Runtime.Serialization.Xml": "4.0.10"
Then I'm using HttpClient. Right now (beta7) it doesn't work on Linux or OSX because of https://github.com/dotnet/corefx/issues/2155.

Windows 8 FormDataCollection not found in System.Net.Http.Formatting class

I am developing a Windows 8 Application and I would like to use System.Net.Http.Formatting.FormDataCollection to send the data to the server.
I've installed Microsoft ASP.NET Web API Client Libraries 4.1.0-alpha-120809 from Nuget.
However, when I try to use FormDataCollection from System.Net.Http.Formatting class, it doesn't recognize it.
What am i missing?
You shouldn't really be using FormDataCollection for sending form content as it does not derive from HttpContent. Do this instead.
var form = new Dictionary<string, string>();
form.Add("foo","bar");
form.Add("boo","baz");
var response = await httpClient.PostAsync(new Uri("http://example.org/"), new FormUrlEncodedContent(form));
System.Net.Http and System.Net.Http.Formatting are two different assemblies. Make sure that you are addding System.Net.Http.Formatting assembly as a reference as well. It worked for me.

Resources