asp.net-web-api - 看不到为什么带有 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;
}
保罗
解决方案
通过将“/”替换为“-”来创建不带特殊字符“/”的 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
推荐阅读
- python - 使用 for 循环函数进行数据抓取
- python - 如何在一行中同时使用舍入函数和绝对值函数?
- firebase - (Flutter) 无法使用 Cloud Storage 下载图片
- django - Django 更好地加入
- javascript - 有没有更优雅的方式来编写这个 If/or 条件?
- angular - 在angular8中收到错误消息后如何将金额转换为货币管道值
- c# - 如何更改对象类列表中的对象?
- ffmpeg - 在 ffmpeg 字体文件中使用 Google 字体
- php - 什么是 PHP8 JIT 编译器
- swift - 在 SwiftUI 中旋转文本视图及其框架