我正在研究ASP.NET Core 2项目,并希望创建自定义路由。
现在我有一条这样的路线
https://localhost:44354/Question/DisplayQuestion?idqstoinid=21
此路线包含domain/[controller]/[action]/{id?}
但是我想要一条像stackoverflow.com
我想要这个:
domain/[controller]/[id]/title of question
换句话说,我想要:
https://localhost:44354/Question/21/myQuestionTitle
答案 0 :(得分:1)
您可以这样做
[Route("[controller]/[action]")]
public class QuestionController : Controller {
[HttpGet("{id}/{title}")]
public async Task<IActionResult> Index(int id, string title) {
}
}
答案 1 :(得分:0)
您必须添加以下代码以进行路由:
[Route("Question")]
public class QuestionController : Controller
{
[HttpGet("{id}/{title}")]
public async Task<IActionResult> Index(int id, string title)
{
//Your Code
}
}
输入https://localhost:44301/Question/21/myQuestionTitle之类的URL之后,您可以在视图页面上查看视图包的值:
您的控制器操作应为:
参考文献:MSDN - Routing to controller actions
干杯!
答案 2 :(得分:0)
尝试以下修改:
控制器在[Route("Test/{id}/{name}")]
操作的“获取”请求上方使用Details
[Route("Test/{id}/{name}")]
public async Task<IActionResult> Details(int? id ,string name)
{
if (id == null)
{
return NotFound();
}
var test = await _context.TestTab
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
索引视图使用asp-route-{parameter}
传递id
和name
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Bedget)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id" asp-route-name="@item.Name">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}