MVC路由:在子域下不工作

时间:2016-05-25 09:09:24

标签: c# asp.net-mvc asp.net-mvc-routing

我有两个网站,一个是实际的,另一个是虚拟目录。它的工作正常:www.mywebsite.com/AnotherWebsite初始加载。

但是在我尝试使用以下方法进行过滤后,我的查看会重新回到 www.mywebsite.com/Home/Index ,但我需要留下喜欢 www.mywebsite.com/AnotherWebsite/Home/Index

public ActionResult Index(int? pageNumber, string categories) {
    if (!string.IsNullOrEmpty(categories)) {
        Session["Categories"] = categories;
        pageNumber = 1;
    }
     if (sessionCategoriesValue != "all") { 
        return View("AnotherWebsite/Home/Index", results.ToPagedList(pageNumber ?? 1, 15));                         
    }
    else {
        return View(Url.Content("~/")+"AnotherWebsite/Home/Index", results.ToPagedList(pageNumber ?? 1, 15));       

    } 
}

但我的分页工作正常,如www.mywebsite.com/AnotherWebsite/Home/Index?pageNumber=2&categories=null

我的MapRoute就像吼叫:

routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
你可以请一下建议吗?

1 个答案:

答案 0 :(得分:0)

你以前没有尝试过RouteConfig.cs自定义路由吗?

http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

RouteConfig.cs:

public class RouteConfig {

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(name: "AnotherWebsite", url: "AnotherWebsite/{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // this route should take place on top of default routing
        routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }
}

如果这种方式不够满意,只要包含“{controller} / {action} / {id}”路由规则,MapRoute上的url部分就会随时更改。

  • 附录编辑 -

似乎可以使用Request.ServerVariables(subDomain是您想要的子域名)重定向子域名:

Controller.cs

// Note: "HTTP_URL" contains encoded raw URL data
// If you want unencoded version one, use "UNENCODED_URL"
if (String.IndexOf(Request.ServerVariables("HTTP_URL").ToUpper(), subDomain.ToUpper()) > 0) 
{
    return RedirectToAction("youractionname", "yourcontrollername", new { // your action parameters here });
}

或使用“包含”:

if (Request.ServerVariables("HTTP_URL").ToUpper().Contains(subDomain.ToUpper())) {
        return RedirectToAction("youractionname", "yourcontrollername", new { // your action parameters here });
}

如果控制器解决方案无效,请使用IIS重写URL:

<rule name="YourRule" enabled="true">
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HOST}" pattern="- insert your subdomain regex pattern here-" />
</conditions>
<action type="Redirect" url="yourdomain.ext/{R:0}" appendQueryString="true" redirectType="Permanent" /> 
</rule>

参考:https://host4asp.net/top-iis-rewrite-rules/