3

I have followed a SO answer here to implement a custom Claim:

How to extend available properties of User.Identity

However, my problem is that it never returns a value. Here is my implementation:

using System.Security.Claims;
using System.Security.Principal;

namespace Events.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetCustomUrl(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("CustomUrl");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

namespace Events.Models
{
    public class Member : IdentityUser
    {
        public string CustomUrl { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Member> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            userIdentity.AddClaim(new Claim("CustomUrl", this.CustomUrl));
            return userIdentity;
        }
    }
}

And now I tried calling it in a view for testing:

<script>alert(@User.Identity.GetCustomUrl());</script>

The value is always nothing, however if I were to change to @User.Identity.GetUserId() then it would return me the Id.

Have I missed a step somewhere?

Community
  • 1
  • 1
Bagzli
  • 5,388
  • 14
  • 58
  • 124

1 Answers1

1

It is a string so you should use: alert('@User.Identity.GetCustomUrl()'); Note the quotes, because otherwise 'javascript' searches for an object with the name it returns. Also don't forget to escape the value here, if it could contain single quotes itself.

Silvermind
  • 5,271
  • 2
  • 21
  • 39
  • You were correct on that one. However, I'm trying to now understand why would this statement not work: `@Html.ActionLink("Manage my Profile", "Show", "Members", new {id = @User.Identity.GetCustomUrl()}, new {title = "Manage"})` I am trying to get it to produce a `events/Members/Show/abc` link – Bagzli Feb 07 '16 at 17:05
  • Actually ignore my previous comment, for some reason, it started working all of a sudden, I wonder if I was just having a caching issue. – Bagzli Feb 07 '16 at 17:08