简体   繁体   English

ASP.NET MVC-路由适用于/ home,但不适用于/ home / index

[英]ASP.NET MVC - Routing works for /home but not for /home/index

I am trying to add views for a project I completed online. 我正在尝试为我在线完成的项目添加视图。

When I load the default web-page, my Index action in the Home controller loads up. 加载默认网页时,将加载Home控制器中的Index操作。 When I navigate to /home, my Index action in the Home controller loads up. 当我导航到/ home时,将加载Home控制器中的Index操作。 However, when I navigate to /home/index, an error pops up. 但是,当我导航到/ home / index时,会弹出一个错误。

This is my default route in my startup class: 这是启动类中的默认路由:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });
            })

And this is my Index method in my home controller: 这是我的家庭控制器中的Index方法:

public class HomeController : Controller
    {
        private readonly IMovieRankService _movieRankService;

        public HomeController(IMovieRankService movieRankService)
        {
            _movieRankService = movieRankService;
        }

        [HttpGet]
        public async Task<ActionResult> Index()
        {
            var other = await _movieRankService.GetAllItemsFromDatabase();
            return View(other);
        }

My index view: 我的索引视图:

@using Movie_Rank.Contracts;
@model IEnumerable<MovieResponse>

@{
    ViewData["Title"] = "movies";
}

<h2>movies</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.MovieName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Description)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Ranking)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeRanked)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.MovieName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Ranking)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.TimeRanked)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>

When I run the program, my table of movies loads up fine. 当我运行该程序时,我的电影表可以正常加载。 When I put /home into the url, my table of movies loads up fine. 当我将/ home放入url中时,我的电影表可以正常加载。 But when I put in /home/index, it gives this error: 但是当我输入/ home / index时,它会出现此错误:

    NullReferenceException: Object reference not set to an instance of an object.
MovieRank.Libs.Mappers.Mapper.ToMovieContract(MovieDb movie) in Mapper.cs
-
        18. }
        19.
        20. public MovieResponse ToMovieContract(MovieDb movie)
        21. {
        22.     // Returns new MovieResponse which maps proprties of MovieDb (using DynamoDB table attributes
        23.     // For example, MovieName (from MovieResponse class) = movie.MovieName (from MovieDb)
      **24.**   return new MovieResponse
        25.     {
        26.         MovieName = movie.MovieName,
        27.         Description = movie.Description,
        28.         Actors = movie.Actors,
        29.         Ranking = movie.Ranking,
        30.         TimeRanked = movie.RankedDateTime
MovieRank.Services.MovieRankService.GetMovie(int userId, string movieName) in MovieRankService.cs
-
        31. 
        32. // Get a movie from MovieDb in MovieRankRepository and map to MovieResponse
        33. public async Task<MovieResponse> GetMovie(int userId, string movieName)
        34. {
        35.     var response = await _movieRankRepository.GetMovie(userId, movieName);
        36.     // Uses MovieRankRepository response
      **37.**   return _map.ToMovieContract(response);
        38. }
        39.
        40. // Get movies from MovieDb in MovieRankRepository and map to MovieResponse
        41. public async Task<IEnumerable<MovieResponse>> GetUsersRankedMoviesByMovieTitle(int userId, string movieName)
        42. {
        43.     var response = await _movieRankRepository.GetUsersRankedMoviesByMovieTitle(userId, movieName);
MovieRank.Controllers.HomeController.GetMovie(int userId, string movieName) in HomeController.cs
-
        25. }
        26. 
        27. [HttpGet]
        28. [Route("{userId}/{movieName}")]
        29. public async Task<ActionResult> GetMovie(int userId, string movieName)
        30. {
      **31.**   var result = await _movieRankService.GetMovie(userId, movieName);
        32. 
        33.     return View(result);
        34. }
        35. 
        36. [HttpGet]
        37. [Route("user/{userId}/rankedMovies/{movieName}")]

So we know that when you use /Home/Index , it's using this action: 因此,我们知道当您使用/Home/Index ,它正在使用此操作:

public async Task<ActionResult> GetMovie(int userId, string movieName)

That has to do with the route you gave it: 这与您给它的路线有关:

[Route("{userId}/{movieName}")]

Because the route, at this point, doesn't know the type that userId should be, it's matching userId = "Home" and movieName = "Index" . 因为此时路由不知道userId的类型,所以它匹配userId = "Home"movieName = "Index" Then when the values are mapped, the value types don't match, and I assume you're probably getting 0 for userId in the method itself. 然后,在映射值时,值类型不匹配,并且我假设您可能在方法本身中为userId0

Try adding a constraint in the route, to make sure the route is only selected if userId is an int : 尝试在路由中添加约束 ,以确保仅当userIdint时才选择路由:

[Route("{userId:int}/{movieName}")]

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

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