2017-04-10 85 views
0

我的应用程序是一个经典的Asp.Net应用程序,而不是MVC。现在我想添加ApiController到它。Asp.net WebAPI给出错误没有找到与请求URI匹配的HTTP资源

我已新增下列API控制器

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/,它给了我下面的错误,

此XML文件似乎没有任何与其关联的样式信息。文档树如下所示。 找不到与请求URI'http://localhost:52182/api/alfresco/'匹配的HTTP资源。 未找到与名为“alfresco”的控制器相匹配的类型。

请让我知道,如果我做错什么在这里,我试图从计算器所有的解决方案,似乎没有任何在Global.asax.cs中工作

回答

0

更改代码:

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”。所以你必须先安装它。

+0

嘿,非常感谢,它的工作! – avdhoota

相关问题