Asp.net MVC 并重定向到外部站点

发布于 2024-12-23 08:33:08 字数 281 浏览 2 评论 0原文

我已经创建了一个 mvc 应用程序,它工作正常,现在我想添加一些基于 xml 的路由,我不想基于它创建操作,这将在运行中工作。

IE www.lmenaria.com/site1 这将重定向到 www.site1.com www.lmenaria.com/site2 这将重定向到 www.site2.com www.lmenaria.com/site3... 这将重定向到 www.site3.com

无操作 Site1、site2、site3 lmenaric.om,那么路线是什么以及如何重定向到外部站点。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2024-12-30 08:33:08

您可以在控制器上仅使用一个操作来执行此操作,但是您需要一个路由约束,否则您最终会将所有请求路由到同一操作。这是一个示例:

将此路由放在顶部:

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

您的路由约束应如下所示:

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());

    }
}

我在那里放置了一个虚拟逻辑以允许站点,但如何获取该数据取决于您。

控制器动作:

public class SiteRouterController : Controller { 

    public ActionResult Route(string site) { 

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

我希望你明白了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文