2016-07-18 26 views
0

ASP.NET MVC5 IDを使用していて、クレームベース認証を実装しようとしています。'System.Collections.Generic.IEnumerable'型を 'System.Web.Mvc.ActionResult'に暗黙的に変換できません。

私は次のエラーを取得する:

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?)

これは、コードの一部です:

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

- それはビューを返す - それは 'リターンビュー(請求)する必要があります。すなわち、'(ビューで文句を言わない仕事ようにあなたが匿名のオブジェクトを作成するが)またはあなたはjsonをajaxコールに戻していますか?それとも、あなたが他の場所で使う方法ですか? –

答えて

3

を返却する必要がありますそれはMVCコントローラである場合は、モデルとしてIEnumerable<Claim>を受け入れビューを返す必要があります:それは、APIコントローラである場合

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); 
} 

あなたはを返すことができますそれあなたの方法がないさ何

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); 
} 
+0

具体的なクラスの' IEnumerable 'を返すapiルートが完全にOk –

+0

@ jenson-button-eventではない具体的な型がIHttpActionResultを実装していない限りコンパイルします。 –

+0

'public IEnumerable GetClaims()'は私が意図したものです。完璧に受け入れられるWeb APIメソッド。または 'public IEnumerable GetClaims()'匿名を返す場合は –

1

カップルからの例を以下しています。あなたはActionResultのような無名型の列挙可能なものを返そうとしています。一般的に、ActionResultsは、モデルに渡しビュー(かみそりのテンプレート)への参照を返すことを期待:

return View(model); 

あなただけのデータを返すようにしたい場合は、あなたがJsonResult

return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
+0

ありがとう、私はJsonメソッドが働くようにデータを返すだけです。 –

+2

'JsonResult'を返すときに匿名の型が良い(ビューを返すときだけではない) –

関連する問題