gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:22:54 25 4
gpt4 key购买 nike

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

这是网络服务 Controller 类代码:

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

错误指出 Controller 名为 '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}")]

关于c# - 为什么调用 web 服务函数时会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com