【问题标题】:I want to use office 365 Api for my Asp.net with C# non mvc Project我想在我的 Asp.net 中使用 office 365 Api 和 C# 非 mvc 项目
【发布时间】:2016-04-02 16:11:51
【问题描述】:

大家好,我刚开始在我的项目中使用API。 我正在使用带有 C# 的 Asp.Net,它没有 MVC architecture。 我的客户需要将 office 365 API 集成到项目中,以便任何想要访问我们服务的用户都可以通过他们的 office 365 凭据登录。 当我在互联网上搜索它说我需要带有 MVC 的 ASP.net 来使用 office 365 的来源时。请建议可以做什么。

【问题讨论】:

    标签: asp.net-mvc api office365api


    【解决方案1】:

    您可以使用 Active Directory 身份验证库 .NET 轻松地对云或本地 Active Directory (AD) 的用户进行身份验证,然后获取访问令牌以保护 API 调用。在网页表单中,以下代码供您参考:

            protected  void Page_Load(object sender, EventArgs e)
            {
            string authCode = Request.Params["code"];
            if (!string.IsNullOrEmpty(authCode))
            {
                 Authorize(authCode);
            }
    
            string token = (string)Session["access_token"];
            if (string.IsNullOrEmpty(token))
            {
                return;
            }
            try
            {
                // get user name
                getUserName(token);
            }
            catch (AdalException ex)
            {
    
            }
        }
    
        public void getUserName(string token)
        {
            using (var client = new HttpClient())
            {
                //Enable signon and read users' profile
                using (var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/beta/me"))
                {
                    request.Headers.Add("Authorization", "Bearer " + token);
                    request.Headers.Add("Accept", "application/json;odata.metadata=minimal");
                    using (var response = client.SendAsync(request).Result)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                            Response.Write(json["displayName"].ToString());
                        }
                    }
                }
            }
        }
    
        public void Authorize(string authCode) {
            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
    
            // The same url we specified in the auth code request
            string redirectUri = "http://localhost:55065/Default.aspx";
    
            // Use client ID and secret to establish app identity
            ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ClientID"], ConfigurationManager.AppSettings["ClientSecret"]);
    
            try
            {
                // Get the token
                var authResult =  authContext.AcquireTokenByAuthorizationCode(
                    authCode, new Uri(redirectUri), credential, "https://graph.microsoft.com/");
    
                // Save the token in the session
                Session["access_token"] = authResult.AccessToken;
    
    
                Response.Redirect(redirectUri.ToString());
            }
            catch (AdalException ex)
            {
                //return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
            }
        }
        public void signin()
        {
            var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
    
    
            // The url in our app that Azure should redirect to after successful signin 
            string redirectUri = "http://localhost:55065/Default.aspx";
    
    
            // Generate the parameterized URL for Azure signin 
            Uri authUri = authContext.GetAuthorizationRequestURL("https://graph.microsoft.com/", ConfigurationManager.AppSettings["ClientID"],
                new Uri(redirectUri), UserIdentifier.AnyUser, null);
    
            // Redirect the browser to the Azure signin page 
            Response.Redirect(authUri.ToString());
        }
    

    您也可以参考以下链接以在 GitHub 中获取一些使用 O365 API 的示例: https://github.com/dream-365/OfficeDev-Samples/tree/master/samples/Office365DevQuickStart

    但我建议你可以尝试使用 ASP.NET MVC,它的设计考虑了关注点分离和可测试性,你会在这里找到很多带有 O365 的 MVC 示例: Office 365 API code samples and videos

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-22
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多