Get sharepoint current User LoginName in C# MVC

时间:2016-09-01 06:24:21

标签: c# asp.net-mvc sharepoint

I have 2 Apps :

  1. Sharepoint 2013 AS a portal web
  2. MVC App

If i want a single sign on from sharepoint, how can i get the current user that logged in to sharepoint from my MVC App ?

The information might needed :

  • Sharepoint login using windows authentication
  • Flow :
    1. User login in sharepoint web
    2. There is a button to open my MVC App in new tab (by URL)

For now i only know using REST API method. Code Existing :

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(HostURL + "/_api/Web/CurrentUser?Select=id");
request.Method = "GET";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(UserName, Password, DomainName);

But in my code is only get the user that i assigned in network credential. How can i get the current user that logged in to sharepoint from my MVC App ?

Any Method will be accepted as long as i can get the user LoginName. Just tell me what should i do.

Thank you

2 个答案:

答案 0 :(得分:2)

我没有对此进行测试,但这可能会让您进入正确的方向。

move_uploaded_file
希望有所帮助。

修改

using (SPSite site = new SPSite(SPContext.Current.Site.ID)){
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
   string userName = web.CurrentUser.LoginName;
}}

希望这可以解释有关Storm托管提供商的更多信息。

答案 1 :(得分:0)

这在技术上是不可能的。当您的MVC应用程序不是ProviderHostedApp时,您无法获得登录到SharePoint门户的用户。

Sarel的答案只有在您的应用程序是sharepoint解决方案且在sharepoint上下文中运行时才有效。否则,你只能使用当前用途构建一个新的SPSite或SPWeb对象,是的,但它是运行/使用你的MVC应用程序的用户。

<强>更新

当用户在按钮上打开您的应用程序时,单击“从共享点”站点,您必须确保将MVC应用程序的IIS配置设置为“Windows身份验证和用户模拟”。

在这种情况下,打开SharePoint网站并单击链接以打开MVC应用程序的用户是同一个用户。然后,您将能够在MVC应用程序中获得HTTPContext的当前使用。

System.Web.HttpContext.Current.User