2016-07-13 15 views
0

我有這個接受可選參數:獲取指數在我<em>Startup.cs</em>文件從路線

 app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "list", 
       template: "{controller=List}/{action=Index}/{username?}"); 
     }); 

我想這一點:

/列表/

到返回一個視圖。

這:

/list/random_username.12334

返回另一個視圖。

我有這個在我ListController.cs

public IActionResult Index(string username) 
    { 
     if (String.IsNullOrEmpty(username)) 
     { 
      ViewData["Message"] = "user index"; 
     } else { 
      ViewData["Message"] = "Hello " + username; 
     } 

     return View(); 
    } 

但只有不帶參數的指標工作。另一個返回404.

+1

你的模式需要'/ Index'。 – SLaks

+0

@SLaks你是什麼意思? – Cornwell

回答

1

看看你的路線定義。

template: "{controller=List}/{action=Index}/{username?}" 

所以理想的URL將被 list/index/somethinglist或 '列表/索引'。但如果您嘗試list/index(其中您的索引是用戶的名稱),那麼mvc如何知道您的操作方法名稱而非參數值?

如果您確實想要支持list/someusername,您可以考慮在您的操作方法中添加屬性路由。

[Route("list/{username}")] 
public ActionResult Index(string username) 
{ 
    // to do : return something 
} 

現在您可以訪問yoursite/list/someusername

+0

謝謝,那是有效的。但是這樣做不好嗎? IE瀏覽器。使用索引參數? – Cornwell

+0

我不認爲這是一種不好的做法。根據需要使用。 – Shyju