2012-11-09 13 views
6

मैं नियंत्रक फ़ंक्शन के ऊपर [FirstTime] विशेषता डालना चाहता हूं और फिर FirstTimeAttribute बनाना चाहता हूं जिसमें कुछ तर्क है जो जांचता है कि उपयोगकर्ता ने अपना नाम दर्ज किया है या नहीं, और उसे /Home/FirstTime पर रीडायरेक्ट करता है यदि वह नहीं है।नियंत्रक फ़ंक्शन के ऊपर कस्टम विशेषता

तो बजाय कर रही है:

public ActionResult Index() 
{ 
    // Some major logic here 
    if (...) 
     return RedirectToAction("FirstTime", "Home"); 

    return View(); 
} 

मैं बस करना होगा:

[FirstTime] 
public ActionResult Index() 
{ 
    return View(); 
} 

यह संभव है?

उत्तर

10

निश्चित रूप से। जैसे

public class FirstTimeAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if(filterContext.HttpContext.Session != null) 
     { 
      var user = filterContext.HttpContext.Session["User"] as User; 
      if(user != null && string.IsNullOrEmpty(user.FirstName)) 
       filterContext.Result = new RedirectResult("/home/firstname"); 
      else 
      { 
       //what ever you want, or nothing at all 
      } 
     } 
    } 
} 

कुछ करो और बस अपने कार्यों पर [फ़र्स्टटाइम] विशेषता का उपयोग

+0

बहुत बढ़िया है, धन्यवाद बहुत ज्यादा। आपके द्वारा फ़िल्टर किए जाने के बाद एक आकर्षण की तरह काम किया 'filterContext.Result = new RedirectResult (...);' ... धन्यवाद! – Gaui

+1

खुशी है कि मैं मदद कर सकता हूं। पहली जगह में जोड़ने के लिए खेद है; मेरा दिमाग फिसल गया (कुछ और पर काम कर रहा है) – Mihai

0

गुण कोड:

public class FirstTimeAttribute : ActionFilterAttribute, IActionFilter 
     { 
      public override void OnActionExecuting(ActionExecutingContext filterContext) 
      { 
       if (string.IsNullOrEmpty(filterContext.HttpContext.Request[name])) 
       { 
        filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary 
              { 
               { "controller", "Home" }, 
               { "action", "FirstTime" }, 
               { "area", string.Empty } 
              }); 
       } 
      } 
    } 

उपयोग:

[FirstTime] 
public ActionResult Index(string name) 
{ 
    return View(); 
} 
+0

कार्यान्वयन IActionFilter अनावश्यक है। ActionFilterAttribute पहले से ही इस इंटरफेस को लागू करता है, और आपका फर्स्टटाइम एट्रिब्यूट एक्शनफिल्टर एट्रिब्यूट से प्राप्त होता है :) – Mihai

संबंधित मुद्दे