简体   繁体   English

Asp.net core 如何创建自定义路由?

[英]Asp.net core how to create custom route?

I am working on an ASP.NET Core 2 project and want to create a custom route.我正在处理一个 ASP.NET Core 2 项目并且想要创建一个自定义路由。

Now I have a route like this现在我有这样的路线

https://localhost:44354/Question/DisplayQuestion?idqstoinid=21

This route contains domain/[controller]/[action]/{id?}此路由包含domain/[controller]/[action]/{id?}

But I want to have a route like stackoverflow.com但我想要一条像stackoverflow.com这样的路线

I want this :我要这个 :

domain/[controller]/[id]/title of question

In other words I want :换句话说,我想要:

https://localhost:44354/Question/21/myQuestionTitle

You can do like this你可以这样做

[Route("[controller]/[action]")]
public class QuestionController : Controller {
 [HttpGet("{id}/{title}")]
 public async Task<IActionResult> Index(int id, string title) {

 }

}

You have to add below code for routing :您必须添加以下代码进行路由:

[Route("Question")]
public class QuestionController : Controller 
{

 [HttpGet("{id}/{title}")]
 public async Task<IActionResult> Index(int id, string title) 
 {
  //Your Code
 }

}

After enter the URL like https://localhost:44301/Question/21/myQuestionTitle then you can see the view bag values on view page:输入像https://localhost:44301/Question/21/myQuestionTitle这样的URL后,您可以在查看页面上看到查看包值:

在此处输入图片说明

Your Controller action should be :您的控制器操作应该是:

在此处输入图片说明

References : MSDN - Routing to controller actions参考MSDN - 路由到控制器操作

Cheers !!干杯!!

Try the following modification :尝试以下修改:

Controller use [Route("Test/{id}/{name}")] above the 'get' request of Details action控制器在Details操作的 'get' 请求上方使用[Route("Test/{id}/{name}")]

[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);
    }

Index View use asp-route-{parameter} to pass the id and name索引视图使用asp-route-{parameter}传递idname

<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>

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM