Home > Mobile >  In ASP .NET Core API projects, can I route a query string parameter to a controller action without a
In ASP .NET Core API projects, can I route a query string parameter to a controller action without a

Time:11-24

The URL that I'm intending to use is as such https://localhost:44355/?G3s2s as apposed to https://localhost:44355/?value=G3s2s

The problem is at the moment, I can't route that URL to a controller action passing in the desired query string as a parameter like such:

`

[Route("")]
//When the domain is called, this function will be hit and will redirect the user to the associated URL, given that it exists

public IActionResult RedirectShortURL(string bitcode) <--- Attempting to pass "G3s2s"
        {
            //string shortUrl = SiteSettings.ShortUrlDomain   bitcode;
            //Uri enteredUrl = new Uri(shortUrl);
            //bitcode = HttpUtility.ParseQueryString(enteredUrl.Query).ToString();

            
            URL urlObj = _urlDAO.GetURLByBitcode(bitcode);

            if (urlObj != null)
            {
                return Redirect(urlObj.OriginalURL);
            }
            else
            {
                return NotFound();
            }
        }

`

I've attempted to create custom routing endpoints in the Startup.cs which has brought me no luck so far. This is how it currently looks:

`

private void MapRoutes(IApplicationBuilder app, SiteSettings siteSettings)
        {
            //Custom routing
            app.UseEndpoints(routes =>
            {
                routes.MapControllerRoute(
                    name: "URLRedirection",
                    pattern: "{bitcode}",
                    defaults: new { controller = "URL", action = "RedirectShortURL" }
                );
                routes.MapControllerRoute(
                    name: "GetAllURLs",
                    pattern: "api/{controller=URL}",
                    defaults: new { controller = "URL", action = "GetAllURLs" }
                );
            });
        }

`

CodePudding user response:

You could use the HttpRequest object available to all controllers.

Like this:

[Route("")]
public IActionResult RedirectShortURL()
{
    var query = this.Request.Query;
    var queryString = this.Request.QueryString;

    // ...
}
  • Related