Asp.net MVC and redirect to External site

2019-06-04 07:10发布

I have created a mvc application, its working fine, now I want to add some route based on xml, I don't want to create action based on that, that will work on fly.

i.e. www.lmenaria.com/site1 this will redirect to www.site1.com www.lmenaria.com/site2 this will redirect to www.site2.com www.lmenaria.com/site3... this will redirect to www.site3.com

No action Site1, site2, site3 lmenaric.om, so what will be the route and how can I redirect to external site.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-04 08:00

You can do this on controller with only one action but you need a route constraint for that o/w you will end up routing all the request to the same action. Here is a sample:

Put this route at the top:

routes.MapRoute(
    "RedirectSiteRoute",
    "{site}",
    new { controller = "SiteRouter", action = "Route" },
    new { site = new SiteRouteConstraint() }
)

You route constraint should look like this:

public class SiteRouteConstraint : IRouteConstraint {

    public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {

        string[] allowedSites = new[] { "site1", "site2", "site3" };

        return
          allowedSites.Any(x => x == values[parameterName].ToString());

    }
}

I put up a dummy logic there for allow sites but how you get that data is up to you.

The controller action:

public class SiteRouterController : Controller { 

    public ActionResult Route(string site) { 

        return Redirect(string.Format("www.{0}.com", site));
    }
}

I hope you got the idea.

查看更多
登录 后发表回答