Query string not working while using attribute routing

后端 未结 8 2265
無奈伤痛
無奈伤痛 2020-11-27 12:52

I\'m using System.Web.Http.RouteAttribute and System.Web.Http.RoutePrefixAttribute to enable cleaner URLs for my Web API 2 application. For most of

8条回答
  •  执笔经年
    2020-11-27 13:36

    Here's a slight deviant of @bhargav kishore mummadireddy's answer, but an important deviation. His answer will default the querystring values to an actual non-empty value. This answer will default them to empty.

    It allows you to call the controller through path routing, or using the querystring. Essentially, it sets the default value of the querystring to empty, meaning it will always be routed.

    This was important to me, because I want to return 400 (Bad Request) if a querystring is not specified, rather than having ASP.NET return the "could not locate this method on this controller" error.

    [RoutePrefix("api/AppUsageReporting")]
    public class AppUsageReportingController : ApiController
        {
            [HttpGet]
            // Specify default routing parameters if the parameters aren't specified
            [Route("UsageAggregationDaily/{userId=}/{startDate=}/{endDate=}")]
            public async Task UsageAggregationDaily(string userId, DateTime? startDate, DateTime? endDate)
            {
                if (String.IsNullOrEmpty(userId))
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, $"{nameof(userId)} was not specified.");
                }
    
                if (!startDate.HasValue)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, $"{nameof(startDate)} was not specified.");
                }
    
                if (!endDate.HasValue)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, $"{nameof(endDate)} was not specified.");
                }
            }
        }
    

提交回复
热议问题