topcool
topcool

Reputation: 2720

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.

Now I have a route like this

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

This route contains domain/[controller]/[action]/{id?}

But I want to have a route like stackoverflow.com

I want this :

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

In other words I want :

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

Upvotes: 0

Views: 132

Answers (3)

Laxman Gite
Laxman Gite

Reputation: 2328

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:

enter image description here

Your Controller action should be :

enter image description here

References : MSDN - Routing to controller actions

Cheers !!

Upvotes: 0

Xueli Chen
Xueli Chen

Reputation: 12725

Try the following modification :

Controller use [Route("Test/{id}/{name}")] above the 'get' request of Details action

[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

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

}

Upvotes: 0

Tony
Tony

Reputation: 20142

You can do like this

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

 }

}

Upvotes: 1

Related Questions