Asp.net WebAPI 给出错误没有找到与请求 URI 匹配的 HTTP 资源

标签 asp.net asp.net-web-api

我的应用程序是经典的 Asp.Net 应用程序而不是 MVC。现在我想给它添加 ApiController。

我添加了以下 API Controller

public class AlfrescoController : ApiController
{
    [System.Web.Http.Route("api/alfresco")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }
}

我在 Global.asax 中的路由代码如下,

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = System.Web.Http.RouteParameter.Optional }
              );

}

现在当我尝试请求 http://localhost:52182/api/alfresco/ ,它给了我以下错误,

This XML file does not appear to have any style information associated with it. The document tree is shown below. No HTTP resource was found that matches the request URI 'http://localhost:52182/api/alfresco/'. No type was found that matches the controller named 'alfresco'.

如果我在这里做错了什么,请告诉我,我已经尝试了 stackoverflow 中的所有解决方案,似乎没有任何效果

最佳答案

将 Global.asax.cs 中的代码更改为:

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configure(Register);
}

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes(); //Will have preference over the default route below

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

“MapHttpAttributeRoutes”是 Nuget 包中可用的扩展方法:“Microsoft.AspNet.WebApi.Core”。所以你必须先安装它。

关于Asp.net WebAPI 给出错误没有找到与请求 URI 匹配的 HTTP 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328076/

相关文章:

c# - 存储过程和 XML

c# - 如何使用基本的 C# 和 ASP .NET 知识编写此游戏?

jquery - 从 jquery 向 MVC WebAPi 传递多个参数

c# - 返回 IHttpActionResult 与 IEnumerable<Item> 与 IQueryable<Item>

asp.net-web-api - 从 ASP.NET 5 Web API 引用可移植类库 (PCL)

asp.net - 预编译 ASP.Net MVC 2 应用程序的正确方法是什么?

c# - 如何在 Entity Framework 4 Entitydesigner 中正确设置两个对象之间的关联?

c# - 将数据存储在缓存中并在有互联网连接时发布它

c# - CreatedAtRoute路由到不同的 Controller

asp.net-mvc - 在 MVC4 项目中使用 Json.NET 序列化器