问题
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:
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.
来源:https://stackoverflow.com/questions/8634348/asp-net-mvc-and-redirect-to-external-site