为什么调用 web 服务函数时会出错?

Why am I getting an error when calling a webservice function?

我正在编写一个 C# web api 2 webservice 并希望获得一些帮助以从对 web 服务的请求中获取单个项目。

这是网络服务控制器class代码:

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

这是网络服务函数:

// GET: api/Getitem/1
[Route("Getitem")]
[System.Web.Http.HttpGet]
[ResponseType(typeof(Item))]
public async Task<IHttpActionResult> GetItem(int id)
{
    Item item = await db.items.FindAsync(id);
    if (item == null)
    {
        return NotFound();
    }

    return Ok(item);
}

这是 IIS 网站的 uri:

http://localhost/thephase

这是我正在访问的 uri:

http://localhost/thephase/api/Getitem/1

这是浏览器中显示的错误:

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

这里是 WebApiConfig 代码:

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 }
        );
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

错误指出控制器名为 'GetItem',这是不正确的。因此,我认为问题出在 WebApiConfig 路由代码中。

如果我从函数中删除 int id,那么函数将被正确调用。

这是没有参数的相同函数:

// GET: api/Getitemnoparameter
[Route("Getitemnoparameter")]
[System.Web.Http.HttpGet]
[ResponseType(typeof(Item))]
public async Task<IHttpActionResult> GetItem()
{
    Item item = await db.items.FindAsync(1);
    if (item == null)
    {
        return NotFound();
    }

    return Ok(item);
}

以下 uri 正确访问函数:

http://localhost/thephase/api/Getitemnoparameter

所以问题与int参数有关。

有人可以帮我使用参数访问 GetItem 函数吗?

因为您使用的是属性路由,您还需要指定参数才能使其正常工作。

查看本教程以获得更好的理解。

Route Prefixes

[Route("Getitem/{id:int}")]

Id 是一个 intint 是值类型。值类型不能为空。你把参数设置为RouteParameter.Optional,但如果是可选的,必须能赋null。

解决方案:使用可为空的 int

public async Task<IHttpActionResult> GetItem(int? id)