Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Request Querystring values?

My api client code sends an authentication token in the querystring like:

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

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

This is what I am doing now but it is obviously wrong:

The below snippet is inside of my filter that 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")
       {
         ...
       }
}
like image 740
loyalflow Avatar asked Sep 24 '13 14:09

loyalflow


People also ask

What is request QueryString ()?

The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter). Count.

How do you read a QueryString in react?

Get a single Query String value import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };

Can we send query parameters in GET request?

To send query parameters in a GET request in JavaScript, we can pass a list of search query parameters using the URLSearchParams API.


2 Answers

Use the GetQueryNameValuePairs extension method, like so:

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

EDIT To avoid duplicate keys, consider doing a ToLookup:

var queryString = actionContext.Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

Here's a blog post on Lookups: https://www.c-sharpcorner.com/UploadFile/vendettamit/using-lookup-for-duplicate-key-value-pairs-dictionary/

like image 72
Sipke Schoorstra Avatar answered Sep 24 '22 07:09

Sipke Schoorstra


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

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

But then, is passing a token in query string a good practice? Probably not, but it is up to you. HTTP header could be a better option since query string can get logged and cached.

like image 21
Badri Avatar answered Sep 23 '22 07:09

Badri