如何调用WebApi控制器方法?

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

为什么默认情况下它不起作用?我该怎么做才能修复它?

1个回答

8
您不需要在 URL 中包含“get”,因为 GET 是 HTTP 动词的一种类型。默认情况下,如果您在 URL 中输入,则浏览器会发送 GET 请求。因此,请尝试使用 http://localhost:51416/api/。因为如果您取消注释路由配置中的 defaults: new { controller = "UserApiController" ... } 行,则 UserApiController 是默认的 API 控制器。请注意,在指定路由时不需要“controller”后缀,因此正确的 defaults 设置是:defaults: new { controller = "UserApi", id = RouteParameter.Optional }。或者您需要显式指定控制器 http://localhost:51416/api/userapi。您可以开始学习有关 Wep.API 和基于 HTTP 动词的路由约定的知识,请访问 ASP.NET Web API 网站。

尝试访问http://localhost:51416/api时出现了"无法找到资源"的错误,但是http://localhost:51416/api/userapi可以访问:)。如何修复http://localhost:51416/api路由? - angularrocks.com
为了使 http://localhost:51416/api 正常工作,请从路由中 取消注释 此行:defaults: new { controller = "UserApiController", id = RouteParameter.Optional },因为在此处您可以指定路由的默认控制器。 - nemesv
我曾经尝试使用 defaults: new { controller = "UserApiController", id = RouteParameter.Optional },但在调用 localhost:51416/api/ 时仍然出现“找不到资源”的错误。 - angularrocks.com
1
抱歉,您不需要控制器后缀,请尝试使用 new { controller = "UserApi", id = RouteParameter.Optional } - nemesv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接