Search code examples
.netowinkatana

Owin get query string parameters


I am trying to get query string parameters from Owin request. Get operation for parameter 'test' remains empty, although this parameter was in query string. How can I read request parameter from OWIN host?

Call:

localhost:5000/?test=firsttest

Code:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseHandlerAsync((req, res) =>
        {
            string paramTest = req.Get<string>("test");                             
            return res.WriteAsync(paramTest);
        });
    }

Solution

  • Get<T> looks in the OWIN environment dictionary for any key. The individual GET request parameters aren't part of that dictionary though. You could get the complete query string using req.QueryString which is equivalent to req.Get<string>("owin.RequestQueryString") and returns test=firsttest in your case. That could be easily parsed.

    Another option would be something like this:

            app.Use(async (ctx, next) =>
            {
                var param = ctx.Request.Query.Get("test");
                await next();
            });
    

    IOwinRequest implementations provide you with a parsed query string. Note that the object one gets from IOwinContext.Request implements IOwinRequest while the object that is passed to UseHandlerAsync is of a completely different type (Owin.Types.OwinRequest) which neither provides the context nor the parsed query string (afaik).