2016-03-23 8 views
0

Ich habe das folgende Attribut.MVC ActionFilterAttribute feuert die ganze Zeit

ich tun muss:

  1. Rückkehr eine Nachricht an den Browser in der filterContext.Result (ich nehme an, dass Ort, es zu tun)
  2. der Lage sein, eine Aktion zu stoppen
ausgeführt wird

aber nach dem debuggd-Prozess startet der Debugger innerhalb OnActionExecuting Methode, und ich sehe einen Fehler anstelle meiner Seite. Ich dachte, es wird vor der SearchItems Methode ausgeführt werden - warum das passiert?

public class MyAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     bool isValid = false; //some logic here 

     if (!isValid) 
     { 
      filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.PaymentRequired; 

      filterContext.Result = new EmptyResult(); 

      return; 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 

global.asax

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new MyAttribute()); 
    filters.Add(new HandleErrorAttribute()); 
} 

Controller:

public class MainApiController : ApiController 
{ 
    [MyAttribute] 
    [HttpPost] 
    public HttpResponseMessage SearchItems() 
    { 
     ... 
    } 
} 
+0

Können Sie Ihre Frage umformulieren? Es ist mir überhaupt nicht klar. Dein Code und deine Beschreibung von dem, was passiert, scheinen sich alle aufzurichten. – Igor

+0

Vielleicht hilft das bei der Beantwortung Ihrer Frage? [how-to-skip-action-execution-from-actionfilter] (http://stackoverflow.com/questions/9837180/how-to-skip-action-execution-from-actionfilter) oder dieses http: //stackoverflow.com/questions/16822365/web-api-how-to-stop-the-web-pipeline-directly-from-anonactionexecuting-filter – Igor

Antwort

0

Statt einer Emptyresult() sollten Sie

  filterContext.Result = new RedirectResult("/YourRedirect"); 

oder

  filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/PaymentRequired.cshtml" }; 
0

ich die Lösung gefunden, stellte sich heraus, es

verwendet falsche Namensräume waren

statt

public override void OnActionExecuting(ActionExecutingContext filterContext) 

I verwendet:

public class CustomAttribute : System.Web.Http.Filters.ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     if (....) { 
      var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "some message"); 
      actionContext.Response = response; 
     } 
    } 
} 

jetzt funktioniert es wie erwartet.

Verwandte Themen