可以使用自定义的模型验证器实现验证,该验证器检查是否有两个或更多的请求参数同时指定了,并在发现不符合情况时返回验证错误。以下是代码示例:
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Linq;
public class OneParameterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
Dictionary parameters = context.ActionArguments;
int count = parameters.Values.Count(p => p != null);
if (count > 1)
{
string message = "Only one parameter is allowed.";
context.ModelState.AddModelError("MultipleParameters", message);
}
}
}
然后,将该自定义的模型验证器应用于您的控制器操作:
[HttpGet]
[OneParameter]
public IActionResult Get(int? id1, int? id2)
{
// controller action code here...
}
在此示例中,OneParameterAttribute
将在执行 Get
操作之前运行,该操作接受两个可选参数 id1
和 id2
。如果在此操作中同时指定了两个请求参数,则将添加一个验证错误到模型状态中,并返回到客户端。