c# - Web API Controller - 查询字符串中的 'action' 参数

标签 c# asp.net-core

我有以下 Web api Controller

public class ApiController : Controller
{
    [Route("api/test")]
    [HttpGet]
    public string GetData(string key, string action, long id)
    {
        var actionFromQuery = Request.Query["action"];
        return $"{key} {action} {id}";
    }
}

我在查询字符串中需要一个名为“action”的参数,以便它向后兼容现有的 API。
当我发出 get 请求时,操作方法参数被错误地分配给 web api 操作 == Controller 方法名称。

示例获取
http://SERVER_IP/api/test?key=123&action=testAction&id=456
返回“123 GetData 456”

我希望它返回“123 testAction 456”
actionFromQuery 变量已正确分配给“testAction”。
'action' 是不能被覆盖的保留变量吗?
我可以通过更改一些配置来解决这个问题吗?

我没有配置任何路由,只有 services.AddMvc();和 app.UseMvc();在我的启动中。

最佳答案

感谢 this comment 解决了

添加 [FromQuery] 有助于正确分配变量

public class ApiController : Controller
{
    [Route("api/test")]
    [HttpGet]
    public string GetData(string key, [FromQuery] string action, long id)
    {
        return $"{key} {action} {id}";
    }
}

关于c# - Web API Controller - 查询字符串中的 'action' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40861852/

相关文章:

c# - WPF 全局类 MVVM

c# - 为什么在 SerialPort.Open 和 Close 之前使用 Thread.Sleep()?

c# - 如何检查字符串是否不等于多个字符串

visual-studio-2015 - 安装NuGet软件包时未找到项目“默认”错误

c# - 如何在 Redis 中创建持久票证

c# - 使用没有 InvokePattern 或 clickablePoint 的 UI Automation 在单击按钮时调用

c# - 有没有比普通 .settings 文件更高级的常用方法来保存应用程序设置?

ASP.NET Core RC2 找不到 Html 编码器实现

c# - 无法添加 DbContext ASP.Net Core 或使用 Controller 访问数据

c# - 如何将我的 web 应用程序与 Azure AD B2C 连接