11

我刚刚创建了 asp.net mvc 4 应用程序并添加了默认 webapi 控制器

public class UserApiController : ApiController
{
    // GET api/default1
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/default1/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/default1
    public void Post(string value)
    {
    }

    // PUT api/default1/5
    public void Put(int id, string value)
    {
    }

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

然后我试图通过http://localhost:51416/api/get在浏览器中输入来调用方法 get() 但出现错误:

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:51416/api/get'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'get'.
</MessageDetail>
</Error>

我的路线配置:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

为什么默认情况下它不起作用?我能做些什么来解决这个问题?

4

1 回答 1

8

您不需要get输入 URL,因为 GET 是 HTTP 动词的类型。

默认情况下,如果您输入 URL,浏览器会发送 GET 请求。

所以尝试一下http://localhost:51416/api/

因为UserApiController如果您defaults: new { controller = "UserApiController"...在路由配置中取消注释该行,它是默认的 api 控制器

请注意,指定路线时不需要“控制器”后缀,因此正确的dafaults设置是defaults: new { controller = "UserApi", id = RouteParameter.Optional } :)

或者您需要明确指定控制器http://localhost:51416/api/userapi

您可以在ASP.NET Web API 站点上开始了解 Wep.API 和基于 HTTP 动词的路由约定。

于 2012-08-22T11:54:05.593 回答