Sitefinity - C# - Fetch user email and output it in a div

27 Views Asked by At

we are working on a Sitefinity project and trying to figure out how to fetch the user's email that will be displayed inside a div. The website we are working on is old and has quite a few issues, but this seems to be a straightforward request.

This is the code we implemented:

.Master page (client side): includes link to JS and div that will hold the output.

<head runat="server">
    <title></title>
    <!-- Include your other head content -->
    <script src="~/Scripts/userEmailScript.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <!-- Your HTML content -->
        <div class="col-md-12">
            <div id="userEmailDiv"></div>
        </div>
    </form>

JS file

document.addEventListener("DOMContentLoaded", function() {
    var userEmail = "<%= UserEmail %>";
    var userEmailElement = document.getElementById("userEmailDiv");
    if (userEmailElement) {
        userEmailElement.innerText = userEmail;
    }
});

.cs page (server side)

using System;
using Telerik.Sitefinity.Security;
using Telerik.Sitefinity.Security.Model;

namespace YourNamespace
{
    public partial class YourPage : System.Web.UI.Page
    {
        protected string UserEmail { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Your server-side C# code here
                // For example, fetching user email
                UserManager userManager = UserManager.GetManager();
                SitefinityProfile profile = userManager.GetUserProfile(); // Assuming the user is logged in
                UserEmail = profile.Email;
            }
        }
    }
}

Once we refresh the page, we get this value: <%= UserEmail %> instead of the actual email address. My guess is that the problem is in the server side code. I researched the documentation but could not find the solution or a fix. Any insights? Thank you.

1

There are 1 best solutions below

0
Veselin Vasilev On

A few issues here:

  1. This tag:

    <%= UserEmail %>

can only be used in Master page or user control (ascx), but not in .js files.

  1. If you have output cache enabled (which is by default) then the user would see other user's email due to cache.

  2. So, what you can do is in your DomContentLoaded event handler, call this api: /rest-api/login-status which would give you the email and display name of the logged in user (if any). See if your sitefinity version has this api endpoint, if not, you can look at the LoginStatus widget and see which endpoint it is using.