How to get Querystring request values?

My api client code sends an authentication token to the request string:

www.example.com/api/user/get/123?auth_token=ABC123 

I am using the Mvc Web api controller, and I have a filter that checks if auth_token is valid or not, but I'm not sure how to access the querystring request values.

This is what I am doing now, but it is clearly wrong:

Below the snippet is inside my filter, which inherits from:

ActionFilterAttribute

 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { base.OnActionExecuting(actionContext); if (actionContext.Request.Properties.ContainsKey("auth_token") && actionContext.Request.Properties["auth_token"].ToString() == "ABC123") { ... } } 
+8
c # asp.net-mvc asp.net-web-api
source share
2 answers

Use the GetQueryNameValuePairs extension method, for example:

 var queryString = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value); 
+22
source share

In the OnActionExecuting method of the filter, you can access the query string and parse it to get a token.

 var queryString = actionContext.Request.RequestUri.Query; if(!String.IsNullOrWhiteSpace(queryString)) { string token = HttpUtility.ParseQueryString( queryString.Substring(1))["auth_token"]; } 

But then, does the token in the query string pass good practice? Probably not, but it's up to you. An HTTP header may be a better option since the query string can be logged and cached.

+4
source share

All Articles