【问题标题】:Path to Run WebAPI运行 WebAPI 的路径
【发布时间】:2017-05-18 16:43:22
【问题描述】:

我很难用 Browser 或 PostMan 运行 API。问题是路径,所以我收到 404 错误。

这是路径:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

还有 WebAPIConfig:

public static void Register(HttpConfiguration config)
{
    config.EnableCors();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "v{version}/{controller}/{action}/{id}",
        defaults: new {id = RouteParameter.Optional});

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

    config.MessageHandlers.Add(new AuthHandler());
}

这是我需要运行的控制器方法:

public class BankViewerController : ApiController
{
    [HttpGet]
    public List<BuilderList> GetBuilderList()
    {
        //......
    }
}

我尝试的路径是:

http://localhost:62815/BankViewerController/GetBuilderList

它甚至没有到达方法的第一行,它给了我 404 错误,所以我很确定它是路径。

【问题讨论】:

  • 显然您的路由定义包含版本号而您的 URL 没有。

标签: c# asp.net-mvc asp.net-web-api asp.net-web-api-routing


【解决方案1】:

给定路线模板:

routeTemplate: "v{version}/{controller}/{action}/{id}",

您调用了与模板不匹配的错误 URL

http://localhost:62815/BankViewerController/GetBuilderList

你需要类似的东西

http://localhost:62815/v1/BankViewer/GetBuilderList

在调用 URL 时从控制器名称中排除 Controller。这是一个约定。

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多