0

저는 MVC3을 처음 사용하고 SQL Server, EF4 등을 사용하여 기본 Microsoft 멤버십 공급자에서 미리로드 된 계정을 처리해야하는 웹 사이트를 개발 중입니다. 일부 진행 상황이 누군가의 도움을 받아 이루어졌습니다. 그래서, 저를 도와주기 위해 ActionMethodSelectorAttribute가 올바르게 작동합니다.ActionMethodSelectorAttribute가 형식에 액세스 할 수 없습니까?

즉, 누군가의 ID가 프로필 페이지 (www.mysite.com/profile/4)를로드하려는 시도의 일부로서 보았을 때, 그 ID/계정이 '청구 됨'인지 아닌지를 조사 할 것입니다. (내 원래 게시 위치 : MVC3 using routes or using controller logic?)

안타깝게도 ActionMethodSelectorAttribute 내에서 비교적 간단한 데이터베이스 호출을 수행하여 계정 소유권 주장 여부를 결정합니다.

public class UserAccountActivatedAttribute : ActionMethodSelectorAttribute 
    { 
     public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo) 
     { 
      if (controllerContext == null) 
      { 
       throw new ArgumentNullException("controllerContext"); 
      } 
      // get profile id first 
      int id = int.Parse((string)controllerContext.RouteData.Values["id"]); 
      var profile = db.Profiles.Where(q => q.ProfileId == id).FirstOrDefault(); 
      bool isActivated = profile;// some code to get this state 
      return isActivated; 
     } 
    } 

라인 DB를에

var profile = db.Profiles.Where(q => q.ProfileId == id).FirstOrDefault(); 

오류 :

다음은 코드 내 현재 상태입니다. 섹션이 에러 메시지를 다음과 같이

중첩 형 'MySite.Controllers.HomeController.UserAccountActivatedAttribute'

통해 외부 입력 'MySite.Controllers.HomeController'의 비 정적 부재를 액세스 할 수 없다. .. 오류가있는 DB 아래에 강조 표시됩니다.

누군가 ActionMethodSelectorAttribute 내에서이 호출을 할 수없는 이유를 아는 사람이 있습니까? (참고 :. 같은 홈 컨트롤러 안에, 내가 어떤 오류없이 공공 ActionResult 및 ViewResult 클래스에서 많은 유사한 호출을하고있다)

편집

내 HomeController.cs은 다음과 같습니다

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Entity; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using MySite.Models; 

namespace MySite.Controllers 
{ 
public class HomeController : Controller 
{ 
    private MySiteEntities db = new MySiteEntities(); 

    public ActionResult Index() 
    { 
     ViewBag.Message = "Welcome to MySite.com!"; 
     return View(); 
    } 
    //several other ActionResults - create, delete, etc. 

    public class UserAccountActivatedAttribute : ActionMethodSelectorAttribute 
    { 
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo) 
    { 
     if (controllerContext == null) 
     { 
      throw new ArgumentNullException("controllerContext"); 
     } 
     // get profile id first 
     int id = int.Parse((string)controllerContext.RouteData.Values["id"]); 
     var profile = db.Profiles.Where(q => q.ProfileId == id).FirstOrDefault(); 
     bool isActivated = profile;// some code to get this state 
     return isActivated; 
    } 
    } 

... 확실히 홈 컨트롤러에 들어갑니다.

편집 # 2 :

가까이, 값이 항상 진실되고있는 작은 문제.

public class UserAccountActivatedAttribute : ActionMethodSelectorAttribute 
{ 
    private MySiteEntities db = new MySiteEntities(); 

    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo) 
    { 
     if (controllerContext == null) 
     { 
      throw new ArgumentNullException("controllerContext"); 
     } 
     int id = int.Parse((string)controllerContext.RouteData.Values["id"]); 
     var data = new MySiteEntities(); 
     var claimed = db.Claimeds.FirstOrDefault(c => c.ProfileId == id); 
     bool isActivated = claimed.Claimed1.Value != null; 
     return isActivated; 
    } 
} 

claim.Claimed1.Value! = null; 나에게 경고를 준다 : 'bool'타입의 값이 'bool'타입의 'null'과 결코 같지 않기 때문에 표현식의 결과는 항상 '참'이다.

그러나 NULL 값을 처리 할 수있는 항목이 있어야합니다.

+0

'bool'은 절대로 null 일 수 없습니다. 'bool? '만이 null이 될 수 있습니다. 클레임 .1. 'bool'또는 'bool?'유형의 값을 지정하시오. 그것이'bool' 인 경우 null이 될 수 없기 때문에 널 확인이 필요 없습니다. 반면에 'bool?'인 경우 다음을 사용하여 null을 확인하십시오 :'bool isActivated = claims.Claimed1.Value.HasValue; ' – danludwig

+0

어떻게 든 나는 그것을 놓쳤지 만, 나는 또한 그것을 사용할 것입니다. –

답변

1

귀하의 코드가 실제로 이와 같이 보입니다. 맞습니까?

public class HomeController : Controller 
{ 
    public class UserAccountActivatedAttribute : ActionMethodSelectorAttribute 
    { 
     ... 
    } 
} 

속성 클래스를 컨트롤러 내에 중첩하지 않고 첫 번째 수준의 클래스로 만들어야합니다. 그런 다음 자신의 db 인스턴스를 제공해야합니다.class 속성은 컨트롤러 클래스 내에서 중첩 될 때, 그것은 db 인스턴스 변수를 액세스 할 수 있기 때문에 정적 변수 없기 때문에

public class HomeController : Controller 
{ 
    ... 
} 

public class UserAccountActivatedAttribute : ActionMethodSelectorAttribute 
{ 
    private readonly CustomDbContext db = new CustomDbContext(); 

    public override bool IsValidForRequest(ControllerContext controllerContext, 
     MethodInfo methodInfo) 
    { 
     // original code here 
    } 
} 

이유이다. 속성은 실제로 중첩 된 클래스가 아니어야하며 별도의 인스턴스 변수가 있어야합니다. 즉, 컨트롤러의 db 변수를 static으로 만들어 해결하지 마십시오.

+0

아하! 난 몰랐어. 내 질문을 편집하여 실제 모습을 보여준 다음 조사를 시도합니다. 고마워, 댄! –

+0

아직 HomeController 내부에 있지만 ActionMethodSelectorAttribute에 종속 된 일부 ActionResults가 여전히 작동하는지 확인해야합니다. [ActionName ("Profile")] public ActionResult IndexNonActivated (int? id) { return RedirectToAction ("Claimed", 새 {id = id}); } –

+0

ActionMethodSelectorAttribute는 컨트롤러와 동일한 클래스 또는 파일에있을 필요는 없습니다. 액션 메소드의'[UserAccountActivated] 구문을 사용하여 컨트롤러에 속성을 적용합니다. 돌아가서 이것을 다시 읽으십시오 : http://stackoverflow.com/a/10613782/304832 – danludwig

관련 문제