Web api passing array of integers to action method

后端 未结 4 419
滥情空心
滥情空心 2021-01-16 08:28

I have this web api method:

[HttpGet]
[Route(\"WorkPlanList/{clientsId}/{date:datetime}\")]
public async Task

        
4条回答
  •  深忆病人
    2021-01-16 09:03

    tried submitting as an edit to @ManOVision's answer, but it might be more appropriate to show separately.

    In implementing his answer, i found that it does not support binding params that are optional. i've made some updates to support that as shown below.

    the error i was receiving when not passing the param was:

    {
        "Message": "The request is invalid.",
        "MessageDetail": "The parameters dictionary does not contain an entry for parameter 'skus' of type 'System.String[]' for method 'System.Web.Http.IHttpActionResult Get(System.String[], System.String, System.String, System.String, System.String, Boolean)' in 'eGAPI.Controllers.GiftCardsController'. The dictionary must contain an entry for each parameter, including parameters that have null values."
    }
    

    implementation:

    [Route("{skus}")]
    public IHttpActionResult Get([FromUriCsv] string[] skus = null)
    

    updated code:

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        var paramName = Descriptor.ParameterName;
    
        try
        {
            if (actionContext.ControllerContext.RouteData.Values.ContainsKey(paramName))
            {
                var rawParamemterValue = actionContext.ControllerContext.RouteData.Values[paramName]?.ToString();
    
                if (!string.IsNullOrEmpty(rawParamemterValue))
                {
                    var rawValues = rawParamemterValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    
                    actionContext.ActionArguments[paramName] = JsonConvert.DeserializeObject($"[\"{string.Join("\",\"", rawValues)}\"]", Descriptor.ParameterType);
                }
                else
                {
                    actionContext.ActionArguments[paramName] = null;
                }
            }
            else
            {
                actionContext.ActionArguments[paramName] = null;
            }
        }
        catch (Exception)
        {
            actionContext.ActionArguments[paramName] = null;
        }
    
        return Task.FromResult(null);
    }
    
        

    提交回复
    热议问题