我正在使用ASP.NET MVC5 Identity并尝试实现基于声明的身份验证。
我收到以下错误:
无法隐式转换类型' System.Collections.Generic.IEnumerable<<匿名类型:字符串主题,字符串类型,字符串值>>'到' System.Web.Mvc.ActionResult'。存在显式转换(您是否错过了演员?)
这是一段代码:
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;
}
我正在关注http://bitoftech.net/2015/03/31/asp-net-web-api-claims-authorization-with-asp-net-identity-2-1/
的示例答案 0 :(得分:6)
如果它在MVC控制器中,您应该返回一个视图,该视图接受IEnumerable<Claim>
作为模型:
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);
}
如果它在api控制器中,您可以返回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);
}
答案 1 :(得分:1)
一些事情。您尝试将可枚举的匿名类型作为ActionResult
返回。通常,ActionResults希望您返回对传递模型的视图(razor模板)的引用:
return View(model);
如果您只想返回数据,则需要返回JsonResult
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);