.net - 接受 .NET CORE 中的 URL 参数
问题描述
我是 .NET CORE 的新手,我想是否可以更改请求 url 的默认格式。让我解释。我在控制器上有两个 get 方法,用于获取列表并获取 1 个元素的信息
[Route("api/[controller]/")]
[ApiController]
public class Department : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet("{id:int}")]
public string GetDepartamento(int id)
{
return "value";
}
[HttpPost]
public void Post([FromBody] string value)
{
}
}
}
为了调用这些资源你使用
https://localhost:44309/api/department
https://localhost:44309/api/department/1
但我不仅需要为这个控制器使用这种格式,还需要为所有控制器使用这种格式
GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
POST:https://localhost:44309/api/department (data on the body of http call)
PUT:https://localhost:44309/api/department?id=1 (data on the body of http call)
DELETE:https://localhost:44309/api/department?id=1
我正在处理一个新项目(.net core web application MVC),所以启动和程序文件没有被修改。
解决方案
我在控制器上有两个 get 方法,用于获取列表并获取 1 个元素的信息
我需要使用这种格式
GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
如果您想根据查询字符串将请求与预期的操作相匹配,您可以尝试实现自定义ActionMethodSelectorAttribute
并将其应用于您的操作,如下所示。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CheckQueryStingAttribute : ActionMethodSelectorAttribute
{
public string QueryStingName { get; set; }
public bool CanPass { get; set; }
public CheckQueryStingAttribute(string qname, bool canpass)
{
QueryStingName = qname;
CanPass = canpass;
}
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
StringValues value;
routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, out value);
if (QueryStingName == "" && CanPass)
{
return true;
}
else
{
if (CanPass)
{
return !StringValues.IsNullOrEmpty(value);
}
return StringValues.IsNullOrEmpty(value);
}
}
}
将其应用于操作
[HttpGet]
[CheckQuerySting("id", false)]
[CheckQuerySting("", true)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet]
[CheckQuerySting("id", true)]
[CheckQuerySting("", false)]
public string GetDepartamento(int id)
{
return "value";
}
测试结果
推荐阅读
- android - Flutter - 恢复时不要重新启动应用程序
- firebase - 无法将 Firebase 云消息导入 Flutter 应用程序
- django - 我在 Django 的 sub_detail 处收到错误 NoReverseMatch
- pandas - 按最常见的值汇总数据框列
- javascript - 在数组 React 中打印数组对象的正确语法
- woocommerce - wordpress 插件的单词替换
- python - 如何比较两个矩阵的每个元素
- c# - 在进入列表框之前更改数据
- android - Android 将文件下载到 SD 卡
- react-native - TypeError:Super 表达式必须为 null 或 react native 中的函数