Controller Action Methods with different signatures

我们两清 提交于 2020-01-02 06:41:49

问题


I am trying to get my URLs in files/id format. I am guessing I should have two Index methods in my controller, one with a parameter and one with not. But I get this error message in browser below.

Anyway here is my controller methods:

public ActionResult Index()
{
    return Content("Index ");
}

public ActionResult Index(int id)
{
    File file = fileRepository.GetFile(id);
    if (file == null) return Content("Not Found");
    else return Content(file.FileID.ToString());
}

Update: Done with adding a route. Thanks to Jeff


回答1:


You can only overload Actions if they differ in arguments and in Verb, not just arguments. In your case you'll want to have one action with a nullable ID parameter like so:

public ActionResult Index(int? id){ 
    if( id.HasValue ){
        File file = fileRepository.GetFile(id.Value);
        if (file == null) return Content("Not Found");
            return Content(file.FileID.ToString());

    } else {
        return Content("Index ");
    }
}

You should also read Phil Haack's How a Method Becomes an Action.




回答2:


To use the files/id URL format, remove the parameterless Index overload, and add this custom route first so it's evaluated before the default route:

routes.MapRoute(
        "Files",
        "Files/{id}",
        new { controller = "Files", action = "Index" }      
    );

See ASP.NET MVC Routing Overview for the basics of mapping URLs to controller methods and ScottGu's excellent URL Routing article, which has several examples very close to what you want to do.



来源:https://stackoverflow.com/questions/2576570/controller-action-methods-with-different-signatures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!