Accessing post or get parameters in custom authorization MVC4 Web Api

后端 未结 5 1025
轮回少年
轮回少年 2020-11-29 02:38

Is it possible to access post or get parameters via the HttpActionContext object?

I have a set of sensors that loggs data to a web server that provides a REST api.

5条回答
  •  暖寄归人
    2020-11-29 03:24

    Although this question has already been answered. But in case someone else needs it, you can get the querystrings from ActionFilterAttribute like below:

    public class ApiAuthorizationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var queryParameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
    
            var some_value = queryParameters.ContainsKey("some_key")
                        ? queryParameters["some_key"] : string.Empty;
    
            // Log Action Filter call
            base.OnActionExecuting(actionContext);
        }
    }
    

    But usually how I build API authorizations are using headers and a custom verification logic by adding keys (unique strings) to the database against user/client etc.

    public class ApiAuthorizationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var headers = actionContext.Request.Headers.ToDictionary(x => x.Key, x => x.Value);
    
            string api_key = headers.ContainsKey("api_key") ? headers["api_key"].FirstOrDefault() : null;
    
            bool canAccessApi = IsValidKey(api_key);
    
            if (!canAccessApi)
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to this API. Please use a valid key.");
    
            // Log Action Filter call
            base.OnActionExecuting(actionContext);
        }
    
        private bool IsValidKey(string api_key)
        {
            //Build Access Control Logic here using database keys...
            return true;
        }
    }
    

提交回复
热议问题