ElHaix
ElHaix

Reputation: 12996

How to save and access UserContext.Identity (MVC/C#) for use with AngularJS?

In my C#, MVC application, I have a page section with a dropdown. When a selection is made, the MVC controller sets UserContext.Identity.CurrentProject to an object.

This is great for accessing on the server-side, however how do I set this up with Angular so that object is accessible from everywhere?

Thanks.

-- UPDATE --

I have created my own UserContext class in an Infrastructure project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AdminWebsite.Infrastructure
{

    public static class UserContext
    {
        public static CustomPrincipal User
        {
            get
            {
                return (CustomPrincipal)HttpContext.Current.User;
            }
        }

        public static CustomIdentity Identity 
        { 
            get 
            {
                return (CustomIdentity)HttpContext.Current.User.Identity; 
            } 
        }
    }
}

... where I have created my own custom membership/principal/profile/role providers.

From the Razor view, when I do:

<script language="javascript">
    alert("hello: " + @UserContext.Identity.CurrentProject.WebsiteName);
</script>

I get System.NullReferenceException: Object reference not set to an instance of an object. on @UserContext even though I have @using AdminWebsite.Infrastructure at the top of the view.

Global.asax:

In Application_AuthenticateRequest, I have:

        if (Request.IsAuthenticated) 
        {


            // Get the GenericPrincipal identity  
            IIdentity ui = HttpContext.Current.User.Identity;  

            /* Extract Name, isAuthenticated, AuthenticationType from
                the identity of the GenericPrincipal and add them including 
                any custom properties to the custom identity. I added a 
                few extra properties to my custom identity. */

            CustomPrincipal customPrincipal = new CustomPrincipal(ui.Name);

            // Set custom principal 
            HttpContext.Current.User = customPrincipal;

        }

Upvotes: 1

Views: 1462

Answers (1)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67001

On your masterpage somewhere you'll want to set up something like:

var currentProject = '@UserContext.Identity.CurrentProject';
                    // Not sure what version of MVC you're using

Then within your App, you could make it a Constant perhaps:

angular.module('myApp')
    .constant('myConstants', {
        projectName : currenctProject
});

Now you can just inject it everywhere it's needed (as a dependency), and access it by myConstants.projectName.

But this is the very angular-way of doing it. You could also be lazy and just access currentProject as well ;)

Upvotes: 1

Related Questions