2

我在 MVC 2 中遇到了一些模棱两可的操作方法的问题。我尝试实现此处找到的解决方案:ASP.NET MVC 模棱两可的操作方法,但这只是给了我一个“找不到资源”错误,因为它认为我'正在尝试调用我不想调用的操作方法。我使用的 RequiredRequestValueAttribute 类与另一个问题的解决方案中的类完全相同:

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
{
    public RequireRequestValueAttribute(string valueName)
    {
        ValueName = valueName;
    }
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return (controllerContext.HttpContext.Request[ValueName] != null);
    }
    public string ValueName { get; private set; }
}

我的操作方法是:

    //
    // GET: /Reviews/ShowReview/ID

    [RequireRequestValue("id")]
    public ActionResult ShowReview(int id)
    {
        var game = _gameRepository.GetGame(id);

        return View(game);
    }

    //
    // GET: /Reviews/ShowReview/Title

    [RequireRequestValue("title")]
    public ActionResult ShowReview(string title)
    {
        var game = _gameRepository.GetGame(title);

        return View(game);
    }

现在,我正在尝试使用该int id版本,而是调用该string title版本。

4

1 回答 1

2

此解决方案假定您必须绝对使用相同的 URL,无论您是按 ID 还是名称选择,并且您的路由设置为从 URL 向此方法传递一个值。

[RequireRequestValue("gameIdentifier")]
public ActionResult ShowReview(string gameIdentifier)
{
    int gameId;
    Game game = null;
    var isInteger = Int32.TryParse(gameIdentifier, out gameId);

    if(isInteger)
    {
      game = _gameRepository.GetGame(gameId);
    }
    else
    {
      game = _gameRepository.GetGame(gameIdentifier);
    }

    return View(game);
}

更新: 根据微软的说法:“动作方法不能基于参数重载。动作方法可以在使用 NonActionAttribute 或 AcceptVerbsAttribute 等属性消除歧义时被重载。”

于 2011-04-20T17:32:17.903 回答