WebApi controller isn't found

◇◆丶佛笑我妖孽 提交于 2020-01-16 01:10:32

问题


I have an example controller in my WebApi-project:

public class MilestonesController : ApiController
{
    // GET api/milestones
    public IEnumerable<string> Get()
    {
        return new string[] { "M#1", "M#2" };
    }

    // GET api/milestones/5
    public string Get(int id)
    {
        return "M with {id}";
    }

    // POST api/milestones
    public void Post([FromBody]string value)
    {
    }

    // PUT api/milestones/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/milestones/5
    public void Delete(int id)
    {
    }
}

If I try to navigate to it:

http://localhost:59493/api/milestones

I always get the error:

No HTTP resource was found that matches the request URI 'http://localhost:59493/api/milestones'.

No type was found that matches the controller named 'milestones'.

Thank you in advance!

Edit:

my WebApiConfig:

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

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Global.asax:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Possible Solution:

I have deleted my project and I've created a new one (WebAPi project) and now it works. The WebApiConfig etc was the same, so I don't really know what was wrong with my first try


回答1:


you're missing the 'api' section of the url from your route. Try something more like;

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
 );



回答2:


Take a look at where you created that controller. Maybe it is not in the Controllers folder, different namespace or that controller class is nested into another class



来源:https://stackoverflow.com/questions/34116920/webapi-controller-isnt-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!