Web 服务的 C# web api 路由

C# web api route for a webservice

我正在用 C# 编写 Web api,我对访问名为 test.

的函数的正确路径有疑问

这里是 class 定义:

[RoutePrefix("api")]
public class ItemsWebApiController : ApiController

我有一个RoutePrefix如下:

[Route("test")]

这里是函数 test:

[Route("test")]
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
public String test()
{
    return "test";
}

我正在尝试访问以下 url: http://localhost/api/test

上面的 url 显示以下异常:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /api/test

如何访问 test 函数,以便在我的浏览器中显示字符串 "test"

编辑

我已经部署到我的本地 IIS,并且数据库连接字符串工作正常。

本地 IIS 的地址是 http://localhost/

这些是我尝试过的url:

http://localhost/test

http://localhost/api/test

http://localhost/api/test/test

http://localhost/ItemsWebApiController/test

http://localhost/ItemsWebApi/test

以上全部return错误页面。

谢谢

如果你推 [Route("test")] 你的 url 将是 http://address/test

如果您需要 url,例如 http://address/api/test,请更改您的路线,例如 [Route("api/test")]

注意:你还需要加上[HttpGet]

基于您的配置的路线将是:http://address/api/test/test 第一个 test 是来自属性 [Route("test")] 的路由前缀; 第二个 test 是控制器中来自方法

上定义的属性的操作
[Route("test")]
public String test()
{

您必须在 WebAPI 控制器中激活属性路由

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

并在您的应用程序中启动

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

然后你的URL是http://localhost/test,因为这里默认路由不匹配。

Web api 根据您的操作名称推断 http 方法。它不会从 "Test" 知道要使用什么。

the docs

HTTP 方法

Web API 还根据请求的 HTTP 方法(GET、POST 等)选择操作。默认情况下,Web API 查找与控制器方法名称开头的 case-insensitive 匹配项。例如,名为 PutCustomers 的控制器方法匹配 HTTP PUT 请求。

您可以通过使用以下任何属性装饰方法来覆盖此约定:

  • [HttpDelete]
  • [HttpGet]
  • [HttpHead]
  • [HttpOptions]
  • [Http补丁]
  • [HttpPost]
  • [HttpPut]

以下示例将 CreateBook 方法映射到 HTTP POST 请求。

[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }