Asp.net MVC and redirect to External site

时光毁灭记忆、已成空白 提交于 2019-12-07 10:00:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!