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.
Related
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.
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
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.
I'm attempting to set up a Api App (Azure) with Swagger + Swashbuckle as demonstrated by Scott Hanselman at the //Build conference here: http://channel9.msdn.com/Events/Build/2015/2-628.
I have installed (using NuGet) the packages Swagger.Api and Swashbuckle.Core. It hasn't added any controller or settings that I would expect in order to have a swagger page. When I navigate to {baseUrl}\swagger, I get a 404 error.
I would think that since it has a UI it would require a Web App in addition to the Api App, but I've rewatched the demo and Scott clearly says you can add Swagger + Swashbuckle to any Api App. In a 2nd app though I'd think there may be issues with Api discovery. Has anyone set this up yet successfully?
Time rolls on and now Swashbuckle works for vNext (beta8 for me, probably other versions too) - thank you to the team and contributors!
In project.json add the package:
"Swashbuckle": "6.0.0-*",
In startup.cs in ConfigureServices():
services.AddSwaggerGen();
services.ConfigureSwaggerDocument(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "My Super API",
Description = "A Super API using Swagger and Swashbuckle",
TermsOfService = ""
});
});
services.ConfigureSwaggerSchema(options =>{
options.DescribeAllEnumsAsStrings = true;
});
In startup.cs in Configure():
app.UseSwaggerGen();
app.UseSwaggerUi();
Now you can access your API doco - http://domain:port/swagger/ui/index.html
Access your Swagger definition - http://domain:port/swagger/v1/swagger.json
Then assuming you have at least one internet facing dev/uat/staging/prod environment, grab the definition URL then do File-> Import URI at http://editor.swagger.io/ - now you have code-gen for about 20 clients too :)
You can also setup your own code-gen server if you are so inclined too (https://github.com/swagger-api/swagger-codegen), however I leveraged the existing online generator. The online editor also has full model and relationship definitions too at least in my case where I fully defined my model using EF7 (I know, ick... but it's much better than <= EF6 and ServiceStack doesn't support CoreCLR, yet). Depending on the size of your project this could save you a few hours to a few weeks of work documenting, plus it is dynamically updating itself as you code more. And you can use it to test your endpoints too, but I still prefer PostMan.
Full sample project at https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/tree/beta8
Big ups to MrSheepUK
HTH
This answer is now outdated. See the other answer.
There is a nice blogpost describing the problem you have: https://alexanderzeitler.com/articles/Deploying-a-ASP-NET-MVC-6-API-as-Azure-API-App-in-Azure-App-Services/
This describes how you can add the Ahoy! package to an ASP.NET v6 Web Api project and adding this as an API app to Azure.
Here is another source: http://devmeetsbi.ghost.io/help-and-test-page-for-asp-net-web-api-asp-net-5-and-mvc-6/
You did all the right steps, but unfortunately for ASP.NET 5, Swashbuckle doesn't work yet.
You can get Ahoy! which is the next version of Swashbuckle that has ASP.NET v6 support here. That should make everything work.
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.