简体   繁体   中英

asp net web api custom filter and http verb

I'm using a custom filter to validate the content type, like:

        public override void OnActionExecuting(HttpActionContext httpActionContext)
        {
            List<String> errors = new List<String>();

            // a
            if (httpActionContext.Request.Content.Headers.ContentType.MediaType == "application/json")
            {
            }
            else
            {
                errors.Add("Invalid content type.");
            }

                // more checks
        }

The above code is working fine, but the validation should check the request http verb, because it should validate the content type only for put or post. I don't want to remove the custom filter from httpget actions because I have more checks inside it, and I don't want to split the filter in two parts, meaning I have to check the http verb inside the filter, but I can't find how.

Any tips?

You can get the method type (post or put) from this:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    string methodType = actionContext.Request.Method.Method;
    if (methodType.ToUpper().Equals("POST") 
            || methodType.ToUpper().Equals("PUT"))
    {
         // Your errors
    }
}

If you need to get the HTTP Method of the request being validated by the filter, you can inspect the Method property of the request:

var method = actionContext.Request.Method;

I would recommend however that you break the filter apart, as you are quickly headed towards a big ball of mud scenario.

You really should be using the standard HTTPVerb attributes above your controller methods:

[HttpGet]
[HttpPut]
[HttpPost]
[HttpDelete]
[HttpPatch]

MVC Controllers for multiple:

[AcceptVerbs(HttpVerbs.Get, HttpVerbs.Post)]

WebAPI Controlelrs for multiple

[AcceptVerbsAttribute("GET", "POST")]

In the constructor of the action filter, you can pass in options/named parameters that will set the settings for the OnActionExecuting logic. Based on those settings you can switch up your logic.

public class MyActionFilterAttribute : ActionFilterAttribute
{
    private HttpVerbs mOnVerbs;

    public MyActionFilterAttribute(HttpVerbs onVerbs)
    {
        mOnVerbs = onVerbs;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var currentVerb = filterContext.HttpContext.Request.HttpMethod;

        if (mOnVerbs.HasFlag(HttpVerbs.Post)) { }
        else if (mOnVerbs.HasFlag(HttpVerbs.Get)) { }
        base.OnActionExecuting(filterContext);
    }
}

[MyActionFilter(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index()
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM