Add the following Nuget Pacakages,
- Microsoft.AspNet.WebApi.Cors
- SharePointPnPCoreOnline
- Newtonsoft.Json
Right click controllers in the solution explorer -->Add-->Controller-->select WebAPI 2 Controller-empty and click add button give the name mynewcontroller.
Right click Models in the solution explorer -->Add-->New Item-->select Class and click add button give the name mycsom.cs.
Right click Models in the solution explorer -->Add-->New Item-->select Class and click add button give the name mymodel.cs
in MyNewController.cs,
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web.Http;
-
- namespace WebApiwithSharepoint
- {
- public class MyNewController : ApiController
- {
- public async Task SaveData(HttpRequestMessage value)
-
- {
-
- try
- {
- string body = value.Content.ReadAsStringAsync().Result;
- var datalayer = new mycsom();
- mymodel dto = JsonConvert.DeserializeObject<mymodel>(body);
- var setdata = datalayer.mysavedata(dto.Email);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
-
- }
- }
- }
- }
In my model.cs,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace WebApiwithSharepoint
- {
- public class mymodel
- {
- public string Email { get; set; }
- }
-
-
-
-
-
-
-
- }
In mycsom.cs,
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- using Microsoft.SharePoint.Client;
- using SP = Microsoft.SharePoint.Client;
-
- namespace WebApiwithSharepoint
- {
- public class mycsom
- {
- public async Task mysavedata(string value)
- {
-
- try
- {
-
- string SPClientID = "clientid";
- string SPClientSecret = "clientsecret";
- string SitePath = "your site collection";
-
-
-
- using (var clientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(SitePath, SPClientID, SPClientSecret))
- {
- List oList = clientContext.Web.Lists.GetByTitle("Madhan");
- ListItem item = oList.GetItemById(1);
- clientContext.Load(item);
-
- item["Author"] = GetUsers(clientContext, value);
- item.Update();
- clientContext.ExecuteQuery();
- }
-
- }
- catch (Exception ex)
- {
-
- Console.WriteLine("Error Message: " + ex.Message);
- }
- }
- private static SP.FieldUserValue GetUsers(ClientContext clientContext, string UserName) //Method for getting user id for given user mail
- {
- SP.FieldUserValue userValue = new SP.FieldUserValue();
- SP.User updateUser = clientContext.Web.EnsureUser(UserName);
- clientContext.Load(updateUser);
- clientContext.ExecuteQuery();
- userValue.LookupId = updateUser.Id;
- return userValue;
- }
- }
- }
The below is the method for app context authentication:
- var clientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(SitePath, SPClientID, SPClientSecret)
In WebApiConfig.cs which is located in App_start folder:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using System.Web.Http.Cors;
-
- namespace WebApiwithSharepoint
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
- config.EnableCors(new EnableCorsAttribute("SiteCollectionurl", "*", "*"));
-
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
The below line used is for cross website requests,
- config.EnableCors(new EnableCorsAttribute("SiteCollectionurl", "*", "*"));
In the sharepoint page it will execute Sharepoint operations using user context info, unfortunately it's a standalone application so we didn't get the context here. So to run the Sharepoint operation in csom either we need to provide credentials or client secret and the client id.
Here we are following the Sharepoint app concept to get context for running csom code. To register a new app you need to route to this url /_layouts/15/appregnew.aspx from your site collection.
Navigate to that url and click the generate button. After copying the clientid and client secret in local notepad for future reference and clicking create once the app is created, we need to provide scope for that. Navigate to _layouts/15/appinv.aspx from your site collection,
In this give the already-registered client id and click lookup, and it fetches all the details of the app. In the bottom of the page there is a textarea box for the scope of permision. Give the required permission in the form of xml format -- the permisions are
here.
When you click on Create you'll be presented with a permission consent dialog. Press "Trust It" to grant the permissions,
For details about app registration visit
here.
This is purely run with app context so if you do any operations in Sharepoint list or library, the created and modified field is mapped as Shareppoint app instead of user name. Provide the client id, client secret, site url in mycsom.cs file. Once completed bulid the solution.
consuming webapi
- var urla = "https://localhost/api/MyNew/SaveData";
- var data={ Email: "User Email" }
- fetch(urla, {
- method : "POST",
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- },
-
- body: JSON.stringify(data)
- }).then(
- response => response.text()
-
- ).then(
- html => console.log(html)
- );
In Post Man or any RestApi clients,
Url
https://localhost/api/MyNew/SaveData
pre-request-script
- var body={
- Email:'Your Email'
- }
- pm.environment.set('req_body',JSON.stringify(body));
Headers
Accept application/json
Content-Type application/json
Body
{{req_body}}
Conclusion
From this article we get some new idea of authenticating Sharepoint with the standalone progam, and also webapi process consumption in Sharepoint. I hope this helps someone. Happy Coding :)