简体   繁体   中英

WebApi Routing causes 404 (Not Found) response

So, this is a simple one. I have done this in the past. But, it seems that I am missing something.

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // Attribute routing.
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Global.asax.cs

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

SomeController.cs

[RoutePrefix("api")]
public class SomeController: ApiController
{
    [Route("some")]
    [HttpGet]
    private HttpResponseMessage GetSome(HttpRequestMessage request)
    {
        ...
    }
}

Now, when I call: http://localhost:54699/api/some , I get the following 404 :

{ "Message": "No HTTP resource was found that matches the request URI ' http://localhost:54699/api/some '.", "MessageDetail": "No type was found that matches the controller named 'some'." }

Folder structure:

在此处输入图片说明

Why is your controller method private this should be public

[RoutePrefix("api")]
public class SomeController: ApiController
{
    [Route("some")]
    [HttpGet]
    public HttpResponseMessage GetSome(HttpRequestMessage request)
    {
    ...
    }
}

Try to move GlobalConfiguration.Configure(WebApiConfig.Register); after MVC's FilterConfig . This is a standard caveat with WebAPI attribute routing.

you have /api in your routing configuration file.

you have mentioned /api as route prefix for controller and then action is "some".

the uri to "some" should be

http://localhost:<port>/api/api/some
[RoutePrefix("api/some")]
public class SomeController: ApiController
{
    [HttpGet]
    public HttpResponseMessage GetSome(HttpRequestMessage request)
    {
    ...
    }
}

You method GetSome is private. Also, I'll modify the RoutePrefix attribute as in the code snippet to avoid rewriting the Route Attribute on each method.

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