Routing


Lose route with chunks in same variable

You can do mapping in the route setup which allows for several parts, various, to be in between fixed values or to have everything after certain point to be added to the same variable, like:

SoapMaster/{*id}

 or if you want to have it between fixed parts:

SoapMaster/{*between}/SoapGuru/{*rest}

Urls like "/SoapMaster/With/Variable/Between/SoapGuru/Rest/Parts"

will have the following variable values:

Between: "/With/Variable/Between"
Rest: "/Rest/Parts"

 

Debugging route configuration

With the following code you will be able to read the route configuration from a log file. Feed the current HTTP-Context into this wrapper and the read the routes from it.

var ctx = new HttpContextWrapper(Context);
foreach (Route rte in RouteTable.Routes)
{
    if (rte.GetRouteData(ctx) != null)
    {
        if (rte.RouteHandler.GetType().Name == "MvcRouteHandler")
        {
            _log.DebugFormat(string.Format("Followinge: {1} for request: {0}", Context.Request.Url, rte.Url));
        }
        else
        {
            _log.DebugFormat(string.Format("Ignoringroute: {1} for request: {0}", Context.Request.Url, rte.Url));
        }
        break;
    }
}

 

Adding multiple action methods to WebAPI

If you for any reason want to be able to use WebAPI like a normal controller, with action names constructed by you, its possible to do so by chaning in the RouteConfiguration of your project.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
        );
    }
}

 

 


Published: 2016-08-25