2016-09-21 52 views
1

我正在嘗試在URL中傳遞string參數的簡單示例,該示例中沒有使用queryString。首先,我增加了一個新的MapRouteRouteConfig.cs文件不能將字符串作爲ASP.Net中的參數傳遞MVC

  routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
      routes.MapRoute(
        name: "app", 
        url: "{controller}/{action}/{name}" 
      ); 

和位指示我

public class AppController : Controller 
    { 
     public string Index(string name) 
     { 
      return HttpUtility.HtmlEncode("Hello " + name); 
     } 
    } 

但視圖不顯示的字符串參數。例如像這樣的網址 http://localhost:59013/App/Index/Ali只返回Hello

enter image description here

能否請您讓我知道爲什麼發生這種情況?

更新

routes.MapRoute(
     name: "app", 
     url: "{controller}/{action}/{name}", 
     defaults: new {action = "Index" } 
); 
    routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
+5

更改註冊路線的順序。默認必須是最後一個。 **但**,你的'應用程序'路線模式是錯誤的,並且將始終與默認路線相沖突。你最好改變它的模式爲'url:「App/Index/{name}」'(或者更友好的'url:「App/{name}」'')'defaults:new {controller =「App」 ,action =「Index」}'。 – haim770

+0

感謝Haim770,你是正確的改變自定義路由優先級解決了這個問題,但我怎麼能擺脫url中的'\ index'?我已經添加了'defaults:new {action =「Index」}'但是當我嘗試像'http:// localhost:59013/App/Ali /' –

+0

這樣的錯誤時,我得到錯誤請將修改後的路線添加到問題 – haim770

回答

2

首先,你需要改變你的註冊路線的順序,以便默認將是最後一次。

其次,您的app路由模式是錯誤的,並且將始終與默認路由相沖突。你最好的模式改變爲

url: "App/Index/{name}" 

或許來的更友好

url: "App/{name}" 

都與

defaults: new { controller = "App", action = "Index" } 

使您的路線將如下所示:

routes.MapRoute(
    name: "app", 
    url: "App/{name}", 
    defaults: new { controller = "App", action = "Index" } 
); 

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

MSDN

+0

但仍無法使用? –

+0

@MonaCoder,你的路線看起來完全一樣嗎?你在嘗試什麼網址? – haim770

+0

我得到'/'Application.'錯誤服務器錯誤我修改了默認值,但仍然無法登陸頁面沒有索引 –

相關問題