asp.net-mvcasp.net-identityclaims-based-identity

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Web.Mvc.ActionResult'


I am playing around with ASP.NET MVC5 Identity and trying to implement claims based authentication.

I get the following error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<<anonymous type: string subject, string type, string value>>' to 'System.Web.Mvc.ActionResult'. An explicit conversion exists (are you missing a cast?)

This is the piece of code:

public ActionResult GetClaims()
{
    var identity = User.Identity as ClaimsIdentity;
    var claims = from c in identity.Claims
                 select new
                 {
                     subject = c.Subject.Name,
                     type = c.Type,
                     value = c.Value
                 };
    return claims;
}

I am following an example from http://bitoftech.net/2015/03/31/asp-net-web-api-claims-authorization-with-asp-net-identity-2-1/


Solution

  • If it is in a MVC controller you should return a view, which accepts IEnumerable<Claim> as model:

    public ActionResult GetClaims()
    {
        var identity = User.Identity as ClaimsIdentity;
        var claims = from c in identity.Claims
                     select new
                     {
                         subject = c.Subject.Name,
                         type = c.Type,
                         value = c.Value
                     };
        return View(claims);
    }
    

    If it is in a api controller you can return IHttpActionResult

    public IHttpActionResult GetClaims()
    {
        var identity = User.Identity as ClaimsIdentity;
        var claims = from c in identity.Claims
                     select new
                     {
                         subject = c.Subject.Name,
                         type = c.Type,
                         value = c.Value
                     };
        return Ok(claims);
    }