简体   繁体   中英

Asp.net WebAPI Gives error No HTTP resource was found that matches the request URI

My application is a classic Asp.Net application and not MVC. Now i want to add ApiController to it.

I have added following 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)
    {
    }
}

My routing code in Global.asax is like below,

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 }
              );

}

Now when i try to request http://localhost:52182/api/alfresco/ , it gives me following error,

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'.

Please let me know if i am doing anything wrong here, i have tried all the solutions from stackoverflow, nothing seems to work

Change code in Global.asax.cs to:

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" is an extension method available in the Nuget Package: "Microsoft.AspNet.WebApi.Core". So you will have to install that first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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