繁体   English   中英

调用WebAPI GET产生404找不到

[英]Call WebAPI GET yielding 404 not found

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

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

手动添加“ Controllers”文件夹。

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之后,它应该为我自动添加一些隐藏的路由。

在此处输入图片说明 在此处输入图片说明

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

因此,这里有两种解决方法(使用GlobalConfiguration实例):

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

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

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

 config.MapHttpAttributeRoutes();

过度行动

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

至于添加软件包,它仅为您提供WebAPI所需的相关dll,而不会进行任何其他更改

您还可以通过Action属性[HttpGet("")]定义控制器的默认行为。

您需要更新操作:

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

作为提示, Postman是测试api请求的好工具,.NET文档也建议您使用该工具,请参见此处

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

  1. Global.asax中
  2. 通过App_Start注册API路由
  3. 属性和约定路由不能混合在一起
  4. 一旦进入属性,就必须为每个方法声明属性。
  5. 尽管Api控制器可以放置在任何位置/文件夹中,并且可以在不带“ Controller”后缀的情况下进行命名,但是它必须具有类的“ Controller”后缀,即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);
        }
    }

通常在App_Start中的类中定义的API路由注册,约定名称为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会感到困惑,这是一个很好的阅读资料 答案是否定的,您不需要MVC即可进行WebApi。

暂无
暂无

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

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