0

I have the followin attribute.

I need to do:

  1. return a message to the browser in the filterContext.Result (I suppose it's that place to do it)
  2. be able to stop an action being executed

but, after start the debuggind process, the debugger steps inside OnActionExecuting method, and I see an error instead of my page. I thought it's gonna be executed before the SearchItems method - why that happens ?

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()
    {
        ...
    }
}
Tony
  • 12,405
  • 36
  • 126
  • 226
  • Can you rephrase your question? It is not clear (to me) at all. Your code and your description of what is happening all appear to line up. – Igor Mar 23 '16 at 19:46
  • Maybe this helps answer your question? [how-to-skip-action-execution-from-an-actionfilter](http://stackoverflow.com/questions/9837180/how-to-skip-action-execution-from-an-actionfilter) or this http://stackoverflow.com/questions/16822365/web-api-how-to-stop-the-web-pipeline-directly-from-an-onactionexecuting-filter – Igor Mar 23 '16 at 19:52

2 Answers2

0

Instead of an EmptyResult() you should

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

or

            filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/PaymentRequired.cshtml" };
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
0

I found the solution, it turned out there were incorrect namespaces used

instead of

public override void OnActionExecuting(ActionExecutingContext filterContext)

I used:

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

now it works as expected.

Tony
  • 12,405
  • 36
  • 126
  • 226