No HTTP resource was found that matches the request URI in Web API

前端 未结 4 1135
闹比i
闹比i 2021-02-03 21:15

I have configured my WebApiConfig like this:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: \"DefaultApi\"         


        
4条回答
  •  别跟我提以往
    2021-02-03 21:38

    what is the name of your controller and action ?

    The URL should be

    http://localhost:8598/api/Controller/Action
    

    It does not map to the Route Configuration you have specified, hence the pipeline is unable to locate the correct Controller. The /id should not be in the path it must be in the body or the query parameters ( I got stumped in haste !!)

    Example : -

    public class FooController : ApiController
        {
            public int GetIndex(int id)
            {
                return id;
            }
        }
    
    localhost:58432/api/foo/GetIndex?Id=1
    
    O/P :- 1
    

    Note:- If your action name is GetIndex then the URL must be GetIndex not just Index. Optionally you can specify the [HttpGet] attribute for the action.

    If you have the following as well in your WebApi.config

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

    Then http://localhost:58432/api/foo?Id=1 would also be a legitimate route. Not sure if you would want that.

    Also, With WebAPI as far as possible stick to non action based routing , MVC is meant for that. It is not the recommended way.

提交回复
热议问题