【问题标题】:Call WebAPI GET yielding 404 not found调用 WebAPI GET 产生 404 未找到
【发布时间】:2018-04-18 04:18:00
【问题描述】:

VS 2017,新建,项目,C#,ASP.NET Web 应用,ASP.NET 4.5.2 空模板。

Webforms、MVC 和 WebAPI 的未选中文件夹和参考。后来通过 Nuget 添加了 MS WebApi v5.4.2。

手动添加“控制器”文件夹。

xController.cs:

namespace v1.MyApiCallTheirApi.api
{
    public class xController : ApiController
    {
        // GET api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

index.html:

<body>
    <input type="button" value="Go" onclick="go()"/>
    <script type="text/javascript">
        function go()
        {
            alert("lafdla");
            $.ajax({
                type: "GET",
                url: "/api/x", 
                success: alert("ok")
            });
        }
    </script>
</body>

$.ajax 调用总是返回 404。已经检查了 thisthat 和许多其他的。到目前为止,我唯一的怀疑是它可能需要一个 Global.asax 来进行路由配置,但我认为在添加 API 后它应该为我自动添加一些隐藏的路由。

【问题讨论】:

  • 看起来你正在混合约定和配置。
  • 在调试模式下运行您的应用程序并尝试在新的浏览器窗口中点击 URL“localhost:55353/api/x”。仍然得到 404?
  • @Dilish 正确。
  • @KennethK。抱歉,没听懂。

标签: c# api


【解决方案1】:

现在您的应用程序不知道路由是如何创建的。 MVC 无法自动知道,除非您提供每种代码所在位置的指针。

因此有两种方法(使用 GlobalConfiguration 实例):-

a) 基于约定,使用地图路由方法。没有其他地方需要任何进一步的更改。

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

b) 使用控制器方法上的属性来定义实际路由。然后在每个action方法上添加route属性

 config.MapHttpAttributeRoutes();

过度操作

[Route('api/myentity/get')
public entity GetEntity() { }

至于添加包,它只为您提供WebAPI所需的相关dll,不做任何更改

【讨论】:

  • 相信我想念 Global.asax 和路由。所以添加了两个有趣的Application_Start 在我的 index.html 对 GET 的请求之后执行。嗯
【解决方案2】:

你也可以通过Action属性[HttpGet("")]来定义控制器的默认动作。

您需要更新您的操作:

// GET api/<controller>
[HttpGet("")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

作为提示Postman 是一个很好的工具来测试您的 api 请求,这也是 .NET 文档的推荐,请参阅here

【讨论】:

  • 还要确保您没有任何特殊的代理设置会干扰您的请求。
【解决方案3】:

总结我的问题的原因和解决方案:

  1. Global.asax
  2. 通过 App_Start 注册 API 路由
  3. 属性和约定路由不能混合在一起
  4. 一旦使用属性,您必须为每个方法声明属性。
  5. 虽然 Api 控制器可以放置在任何位置/文件夹,并且可以命名任何没有“控制器”后缀的名称,但它必须具有“控制器”后缀的类,即 public class v1Controller : ApiController,只是 public class v1 : ApiController 不起作用。李>

Global.asax 是可选的,但它就像一个项目的 _init(),所以这里是必须的,因为 API 需要路由。无论这个Api是被项目内还是项目外调用,只要它命中内置的App_Start就会初始化项目的一切。

public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }

API路由注册通常在App_Start中定义一个类,约定名称是WebApiConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Either this Attribute Routing
            config.MapHttpAttributeRoutes();

            // Or this conventional Routing, but not together.
            config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

从 Nuget 添加新包不会自动配置/添加必要的项目 进行投影。

MS WebApi 是基于 MVC 路由开发的,如果需要 MVC 就很困惑,这里有一个很好的reading。答案是否定的,你不需要 MVC 来做 WebApi。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2022-01-22
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多