如何防止随机查询匹配到用 [Route('')] 注释的操作?

How to prevent random queries from being matched to an action annotated with [Route('')]?

我目前有这个控制器

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

我只想匹配以下 3 个 url:

  1. api/HomeidAnotherId都为空)
  2. api/Home?id=1(只有 Anotherid 为空)
  3. api/Home?AnotherId=1(只有 Id 为空)

其他网址应 return unregistered routeserror。目前,api/Home?asdfanyquery 也 return 匹配,这不是我想要的。

如何重写控制器以使路由只匹配上面的 3 个 url?

你说的条件api/Home?asdfanyquery会落入default Route。即id和anotherid为null。 试试下面的

[RoutePrefix("api/Home")]
    public class HomeController : ApiController
    {
        [HttpGet]
        [Route("{id=id}/{AnotherId=AnotherId}")]
        public bool GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
        {

            return true;
        }
    }
  1. api/Home?asdfanyqueryapi/Home - idAnotherId 均为空)
  2. api/Home?id=1(只有 Anotherid 为空)
  3. api/Home?AnotherId=1(只有 Id 为空)

我按照评论中的建议结束了 并像这样应用它:

public class InvalidQueryStringRejector : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var arguments = actionContext.ActionArguments.Keys;

        var queryString = actionContext.Request.GetQueryNameValuePairs()
            .Select(q => q.Key);

        var invalidParams = queryString.Where(k => !arguments.Contains(k));

        if (invalidParams.Any())
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new
            {
                message = "Invalid query string parameters",
                parameters = invalidParams
            });
        }
    }
}


[RoutePrefix("api/Home")]
public class HomeController : ApiController
{
     [InvalidQueryStringRejector] //The custom created ActionFilterAttribute
     [HttpGet]
     [Route("")]
     public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id = null, [FromUri]int? AnotherId = null)
     {
         if (!ModelState.IsValid) //From ApiController.ModelState
         {
              return BadRequest(ModelState);
         }
     }
}