如何通过URL零件或Querystring绑定WebAPI控制器操作参数

发布于 2025-01-27 18:53:30 字数 552 浏览 2 评论 0原文

我的API方法是这样定义的:

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    [HttpGet]
    [HttpGet("{itemType}/{itemId}")]
    public IActionResult Get(string itemType, string itemId)
    {
        return Ok($"{itemType}/{itemId}");
    }
}

调用此作品:

/api/items/person/0123

通过 querystring 调用操作导致unprocessentity

/api/items?itemType=person&itemId=0123

我如何定义我的操作方法,以便它接受两种类型的输入?

I have an API method defined as such:

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    [HttpGet]
    [HttpGet("{itemType}/{itemId}")]
    public IActionResult Get(string itemType, string itemId)
    {
        return Ok(
quot;{itemType}/{itemId}");
    }
}

Calling this works:

/api/items/person/0123

Calling the action by querystring results in UnprocessableEntity

/api/items?itemType=person&itemId=0123

How can I define my action method so that it accepts both types of input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

预谋 2025-02-03 18:53:30

您可以尝试这样的尝试,以便您的第一个路由将允许您使用Querystring,并且第二个路由将允许通过属性路由将值绑定到变量。

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    [HttpGet("")]
    [HttpGet("{itemType}/{itemId}")]
    public IActionResult Get(string itemType, string itemId)
    {
        return Ok($"{itemType}/{itemId}");
    }
}

you can try like this, so that the first route will allow you to use querystring and the second one will allow values to be bound to the variables through attribute routing.

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    [HttpGet("")]
    [HttpGet("{itemType}/{itemId}")]
    public IActionResult Get(string itemType, string itemId)
    {
        return Ok(
quot;{itemType}/{itemId}");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文