3

I want to create web api 2 custom attribute with parameter from client, and return data to client there is something wrong.

for example data from client:

{ id : 1, _token : 221 }

for example on server:

//SomeController Action
[CustomActionFilter]
public String Foo(int id)
{
   return id;
}

public class CustomActionFilter : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        //get _token from client httprequest parameter
        //return to client if _token != 221
        //next proccess if _token == 221
        // in real case, will cek token in db and compare it
    }
}

please help how to get _token in CustomActionFilter and return to client error message with json format if _token != 221?

also if no problem along proccess do next proccess?

1 Answer 1

3

You are doing number of things incorrectly. First, ActionFilterAttribute itself has implemented IActionFilter so there's no need to re-implement this interface in your custom attribute again. Second, the token is not passed to the Foo function, so basically you need to change the formal parameters of the Foo function. However, to give you an idea how to do this, check this out:

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var id = actionContext.ActionArguments["id"];
    }
}

Finally, to return an error, you can do this right inside the OnActionExecuting method:

var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "my reasonable error message");
actionContext.Response = response;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.