0

Previously in ASP.NET MVC

<routes>
<add name="VehicleDetailRoute" url="TwoWheeler/VehicleDetail/{id}">
  <defaults controller="Integration" action="VehicleDetail" id="Optional" />
</add>
</routes>

public void RegisterRoutes(RouteCollection routes)
{ //Fill the route table section
  RouteSection routesTableSection = GetRouteTableConfigurationSection();

  if (routesTableSection == null || routesTableSection.Routes.Count <= 0)
    return;

  for (int routeIndex = 0; routeIndex < routesTableSection.Routes.Count; routeIndex++)
  {
    //base on different route, we have created dynamic routes and add in to
    var routeElement = routesTableSection.Routes[routeIndex];

    var route = new Route(
        routeElement.Url,
        GetDefaults(routeElement),
        GetConstraints(routeElement),
        GetDataTokens(routeElement),
        GetInstanceOfRouteHandler(routeElement));

    routes.Add(routeElement.Name, route);
  }
}

Here, Customer see TwoWheeler/VehicleDetail/ on browser but internally it's consider controller as Integration and action as "VehicleDetail"

Now in .Net Core, we were created JSON file and want to read. (want migrate into .Net Core 2.0 from ASP.NET MVC). You can change the format or JSON if required.

{
"routes": {
    "VehicleDetailRoute": {
        "url": "TwoWheeler/VehicleDetail/{id}",
        "controller": "Integration",
        "action": "VehicleDetail",
        "id": "Optional"
    }
  }
}
  1. url : Showing on browser
  2. controller : Original Controller
  3. action : original Action
  4. VehicleDetailRoute : route name

So far, i have read configuration in Startup file

public Startup(IConfiguration configuration)
{
  var configurationBuilder = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("routes.json", optional: false, reloadOnChange: true);
   Configuration = configurationBuilder.Build();
}

Added services.AddRouting(); in ConfigureServices

In Configure method, added app.UseStaticFiles();

Build Routing

var routeBuilder = new RouteBuilder(app);

routeBuilder.MapGet("{route}", context =>
{
  var routeMessage = Configuration.AsEnumerable()
                     .FirstOrDefault(r => r.Key == context.GetRouteValue("route")
                     .ToString())
                .Value;

 var defaultMessage = Configuration.AsEnumerable()
                      .FirstOrDefault(r => r.Key == "default")
                      .Value;

 var response = (routeMessage != null) ? routeMessage : defaultMessage;

 return context.Response.WriteAsync(response);
 });
 app.UseRouter(routeBuilder.Build());

Question : Base on URL enter by customer, i want to redirect particulate action. Want to execute below method with dynamic input

app.UseMvc(routes =>
{
  routes.MapRoute(
  name: "default",
  template: "{controller=Integration}/{action=VehicleDetailOnline}/{id?}");
});

Checked below reference : radu-matei.com -- c-sharpcorner -- StackOverflow

1
  • Is there anything that prevents you from using attribute routing? Commented May 22, 2018 at 7:28

1 Answer 1

1

Have you considered using Url rewrite for this? you can either set them up from your hosting server (IIS, Apache, etc.) or use the .Net Core middleware for it.

Check this link for more details on how to use it: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-2.0&tabs=aspnetcore2x

Edit:

Here's some sample code, I'm writing it of my mind, so there will probably be errors, but the general idea should be fine.

You'll probably need to rewrite the url as regex for it to work better, so it would be like this example:

{
"routes": {
    "VehicleDetailRoute": {
        "url": "^TwoWheeler/VehicleDetail/(.*)",
        "controller": "Integration",
        "action": "VehicleDetail",
        "id": "Optional"
    }
  }
}

Then the setup code would be like this:

public void Configure(IApplicationBuilder app)
{
    var options = new RewriteOptions();
    foreach(var rule in redirectRules){
        options.AddRewrite(rule.url,rule.controller+'/'+rule.action+"/$1")
    }    
    app.UseRewriter(options);

    app.Run(context => context.Response.WriteAsync(
        $"Rewritten or Redirected Url: " +
        $"{context.Request.Path + context.Request.QueryString}"));
}

An easy explanation for what happens is that when request starts with TwoWheeler/VehicleDetail/ this part would be changed to Integration/VehicleDetail/

I really suggest you look around Url Rewrite modules in your web server to see all the tricks you can do with it.

Sign up to request clarification or add additional context in comments.

7 Comments

Do you have any demo regarding this?
I don't have a demo right now, but I can work some code out for you later today.
Thank you mate. Much appreciated.
Here, Able to see "Rewritten or Redirected Url: ..." on white page, but I want to redirect particulate URL.
Well, you have to remove the app.Run since it'll short-circuit your request here, I had it there for demo. Remove it and use your normal setup after that (MVC, or whatever middleware you're using).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.