本文介绍了如何从Xamarin.Forms移动应用程序到本地SharePoint Server 2016进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

Hi All,

我正在尝试使用本地SharePoint服务器在Xamarin.Forms移动应用中进行身份验证.我正在关注Microsoft SharePoint文档:

I am trying to do authentication in my Xamarin.Forms mobile app with on-premise SharePoint server. 
I am following Microsoft SharePoint documentation:

示例代码为:

字符串SharePointUrl =目标SharePoint网站";

string SharePointUrl = "Target SharePoint site";

私有void AuthenticateToSharePoint(对象发送者,RoutedEventArgs e)
{
ODataAuthenticator odataAt =新的ODataAuthenticator(","");
odataAt.CookieCachingEnabled = true;
odataAt.AuthenticationCompleted + =新的EventHandler(odataAt_AuthenticationCompleted);
odataAt.Authenticate(新的Uri(SharePointUrl,UriKind.Absolute));
}

private void AuthenticateToSharePoint(object sender, RoutedEventArgs e)
{
ODataAuthenticator odataAt = new ODataAuthenticator("", "");
odataAt.CookieCachingEnabled = true;
odataAt.AuthenticationCompleted += new EventHandler(odataAt_AuthenticationCompleted);
odataAt.Authenticate(new Uri(SharePointUrl, UriKind.Absolute));
}

void odataAt_AuthenticationCompleted(对象发送者,AuthenticationCompletedEventArgs e)
{
HttpWebRequestendpointRequest =(HttpWebRequest)HttpWebRequest.Create(SharePointUrl.ToString()+"/_ api/web/lists");
endpointRequest.Method ="GET";
endpointRequest.Accept ="application/json; odata = verbose";
EndpointRequest.CookieContainer =(发送者为ODataAuthenticator).CookieContainer;

void odataAt_AuthenticationCompleted(object sender, AuthenticationCompletedEventArgs e)
{
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(SharePointUrl.ToString() + "/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.CookieContainer = (sender as ODataAuthenticator).CookieContainer;

endpointRequest.BeginGetResponse(new AsyncCallback((IAsyncResult res) =>
{
    HttpWebRequest webReq = res.AsyncState as HttpWebRequest;
    WebResponse response = webReq.EndGetResponse(res);

    HttpWebResponse httpResponse = response as HttpWebResponse;
    HttpStatusCode code = httpResponse.StatusCode;
    this.Dispatcher.BeginInvoke(() =>
    {
        MessageBox.Show(code.ToString());
    });
}), endpointRequest);

}

}

我找不到对"ODataAuthenticator"的引用,类,以及"RoutedEventArgs","AuthenticationCompletedEventArgs".在Xamarin.Forms中.
另外,此代码似乎不完整.未提及如何调用事件.
如果有人做了类似的事情,请提供帮助.

I am unable to find reference to "ODataAuthenticator" class, and also "RoutedEventArgs", "AuthenticationCompletedEventArgs" in Xamarin.Forms. 
Also, this code seems incomplete. How to invoke the event is not mentioned.
If someone has done similar to that then please provide help.

推荐答案

ODataAuthenticator和RotuedEventArgs未提供用于指定用法的详细文档.

ODataAuthenticator and RotuedEventArgs not provide detailed document to specify the usage.

但是根据GitHub上的演示,我们可以在移动应用中调用Rest API,如下所示:

But based on the demo in the GitHub, we can call Rest API in mobile app like below:

string SharePointUrl = "https://Target SharePoint site";

private void AuthenticateToSharePoint(object sender, RoutedEventArgs e)
{
    ODataAuthenticator odataAt = new ODataAuthenticator("<Username>", "<password>");
    odataAt.CookieCachingEnabled = true;
    odataAt.AuthenticationCompleted += new EventHandler<AuthenticationCompletedEventArgs>(odataAt_AuthenticationCompleted);
    odataAt.Authenticate(new Uri(SharePointUrl, UriKind.Absolute));
}

void odataAt_AuthenticationCompleted(object sender, AuthenticationCompletedEventArgs e)
{
    HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(SharePointUrl.ToString() + "/_api/web/lists");
    endpointRequest.Method = "GET";
    endpointRequest.Accept = "application/json;odata=verbose";
          endpointRequest.CookieContainer = (sender as ODataAuthenticator).CookieContainer;
    
    endpointRequest.BeginGetResponse(new AsyncCallback((IAsyncResult res) =>
    {
        HttpWebRequest webReq = res.AsyncState as HttpWebRequest;
        WebResponse response = webReq.EndGetResponse(res);

        HttpWebResponse httpResponse = response as HttpWebResponse;
        HttpStatusCode code = httpResponse.StatusCode;
        this.Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show(code.ToString());
        });
    }), endpointRequest);
}

这是通过HttpClient使用Rest API的另一种方法:

And here is another way to consume Rest API with HttpClient:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json.Linq;
namespace SPCSOM
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsync().GetAwaiter().GetResult();
            Console.WriteLine();
            Console.ReadKey();
        }

        static async Task<string> GetDigestAsync(string endPoint, HttpClient client)
        {
            string digest = null;
            HttpResponseMessage response = await client.PostAsync(endPoint, new StringContent(""));
            if (response.IsSuccessStatusCode)
            {
                digest = await response.Content.ReadAsStringAsync();
            }
            JObject rss = JObject.Parse(digest);

            return rss["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }
        static async Task<string> GetListData(string endPoint, HttpClient client)
        {
            string data = null;
            HttpResponseMessage response = await client.GetAsync(endPoint);
            Console.WriteLine("get data status: " + response.IsSuccessStatusCode);
            if (response.IsSuccessStatusCode)
            {
                data = await response.Content.ReadAsStringAsync();
            }
            JObject rss = JObject.Parse(data);
            return rss["d"]["results"].ToString();
            //to do phrase the data
        }
        static async Task RunAsync()
        {
            var username = "administrator";
            var password = "P@ssw0rd";
            var domain = "contoso2016";
            var handler = new HttpClientHandler();
            handler.Credentials = new System.Net.NetworkCredential(username, password, domain);

            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://sp2016/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");//we want to receive JSON rather than XML

            var digest = await GetDigestAsync("/_api/contextinfo", client);
            Console.WriteLine(digest);
            var data = await GetListData("/_api/web/lists/getbytitle('List1')/items", client);
            Console.WriteLine(data);

        }
    }
}

结果:

上面的代码需要与Newton.Json API一起运行,请在此行中的以下行中安装在Nuget Package Console中:

The code above needs to run with Newton.Json API, please install in Nuget Package Console with this line in project:

安装软件包Newtonsoft.Json

Install-Package Newtonsoft.Json

谢谢

最好的问候


这篇关于如何从Xamarin.Forms移动应用程序到本地SharePoint Server 2016进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 17:46