Search code examples
c#asp.net-mvcasp.net-mvc-routingurl-shortener

MVC url shortener


I would like to write a URL shortener using MVC routing. The thing is that I'd like to use the following URL: {host}/?{word}

To do that I use the MapRoute method to have the default go to the correct controller. and it does, but when it passes null to the parameter instead of the content of {word}.

The same thing works correctly if I specify the parameter name, i.e. {host}/?{param-name}={word}

Does anyone know how can I tell MVC that if I don't specify the parameter name then it should go to the first, or a default param?


Solution

  • You can try to write action filter that you put on your action method. Action filter should go trough url query parameters, if it finds parameter with empty value it can bind to parameter.

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
    if (filterContext.HttpContext.Request.Url != null) {
        NameValueCollection urlQuery = System.Web.HttpUtility.ParseQueryString(filterContext.HttpContext.Request.Url.Query);
    
        for (int i = 0; i < urlQuery.Keys.Count; i++ )
        {
            if (urlQuery.Get(urlQuery[i]) == null)
            {
                filterContext.ActionParameters["word"] = urlQuery[i];
            }
        }
    }
    base.OnActionExecuting(filterContext);
    

    }

    You must write some not null conditions so it doesn't fail miserably :)

    Edit: If you want to drop ? just use default mvc url routing, something like this.

    routes.MapRoute(
        "UrlShortener", // Route name
        "{word}", // URL with parameters
        new { controller = "UrlShortener", action = "Fetch",  word="Default", } 
    

    );

    your Controller will accept

    public ActionResult UrlShortener(string word) {
    if (word == "Default") return Content("No word specified");
    
    //some BLL
    return View();
    

    }

    That way your url will be http://hostname/word , if word is not specified it passes "Default".

    If that is what you wanted