首页 > 解决方案 > 看不到为什么带有 2 个日期参数的控制器方法不起作用

问题描述

我有一个非常奇怪和令人沮丧的问题

我有一个带有标准 Web Api 控制器的控制器

[Route("Gateway/[Controller]/[action]")]
public class MyController: Controller
{
    public MyController()
    {
    }

    [ActionName("MyMethod")]
    [System.Web.Http.HttpGet]
    public async Task<IActionResult> MyMethodAsync(int numberParam, DateTime? startDate, DateTime? endDate)
    {

        var parameters = $"numberParam={numberParam}";
        if (startDate != null)
        {
            parameters += $"&startDate={startDate.Value:O}";
        }

        if (endDate != null)
        {
            parameters += $"&endDate={endDate.Value:O}";
        }

//My logic here - not relevant for question

        return result;
    }
}

当我用参数调用我的方法时

?numberParam=1&startDate=01/01/2018&endDate=31/01/2018

endDate 作为 null

为什么是这样?

没有错误,我不知道为什么第二个参数被忽略

无论日期格式如何,这都适用吗?

我不需要时间

使用完整网址时会发生这种情况,例如http://mysite/GatewayController/MyMethod?numberParam=1&startDate=01/01/2018&endDate=31/01/2018

我也通过 HttpClient 调用它,它也不起作用

private static async Task<string> ProcessResponseAsync(HttpResponseMessage response)
{
    var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        return responseText;
    }

    return "Error: " + response.StatusCode + " Content: " + responseText;
}

 private static string GetUrl(string area, string method, string parameters)
 {
   if (!string.IsNullOrEmpty(parameters))
   {
     if (parameters[0] != '?')
     {
       parameters = $"?{parameters}";
     }
   }

   var address = ConfigurationManager.AppSettings["GatewayUrl"];
   var result = $"{address}/{area}/{method}{parameters}";            
   return result;
}

protected async Task<string> ExecuteRequestAsync(string area, string method, string parameters)
{                        
   var url = GetUrl(area, method, parameters);            
   var response = await _httpClient.GetAsync(url).ConfigureAwait(false);
   var result = await ProcessResponseAsync(response).ConfigureAwait(false);

   return result;
}

保罗

标签: asp.net-web-apimodel-view-controllerasp.net-mvc-5asp.net-web-api2

解决方案


通过将“/”替换为“-”来创建不带特殊字符“/”的 url ?numberParam=1&startDate=01-01-2018&endDate=31-01-2018

或使用编码特殊字符,

https://www.w3schools.com/jsref/jsref_encodeURI.asp https://www.w3schools.com/jsref/jsref_encodeURIComponent.asp


推荐阅读