aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
967 stars 334 forks source link

Add query parameter if not present #159

Closed bdebaere closed 6 years ago

bdebaere commented 6 years ago

I have an API to which I would like to add OWIN middleware which reads the query parameters from the URI and adds a specific one if it is not already present.

I have tried multiple different things. And have two issues:

The closest I've gotten is this, but this gives an error stating PathString must start with a /. Probably because it's not meant to be used for adding query parameters?

Can someone point me in the right direction?

public class UrlRewriterMiddleware
{
    private readonly AppFunc _next;

    public UrlRewriterMiddleware(AppFunc next)
    {
        _next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        OwinContext context = new OwinContext(environment);

        if (context.Request.Query.Get("param") != null)
        {
            await _next.Invoke(environment);
        }

        context.Request.Path.Add(new PathString("?$param=1"));

        await _next.Invoke(environment);
    }
}
bdebaere commented 6 years ago

This is a working solution:

public class UrlRewriterMiddleware
{
    private readonly AppFunc _next;

    public UrlRewriterMiddleware(AppFunc next)
    {
        _next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        OwinContext context = new OwinContext(environment);

        if (context.Request.QueryString.Value.Contains("$param"))
        {
            await _next.Invoke(environment);
            return;
        }

        if (context.Request.QueryString.Value != string.Empty)
        {
            context.Request.QueryString = new QueryString($"{context.Request.QueryString.Value}&$param=1");
        }
        else
        {
            context.Request.QueryString = new QueryString("$param=1");
        }

        await _next.Invoke(environment);
    }
}