Action可用于POST,但不能用于GET(查询字符串)
本文关键字:用于 查询 字符串 GET 但不能 POST Action | 更新日期: 2023-09-27 18:28:39
我一直在使用Action来获取报表数据,作为JSON对象,使用jQuery的ajax将表单张贴到报表中没有问题。
但现在我需要根据参数的值返回不同的结果类型。它应该返回JSON、Excel文件(用HTML构建)或PDF文件。因此,我在控制器类上创建了一个嵌套枚举,用于定义可用的返回类型。
但现在,当我尝试从URL调用Action来生成文件时,它会抛出一个ArgumentException
,并显示消息:
The parameters dictionary contains a null entry for parameter 'dataInicio' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult DadosRelatorioResumoLancamentos(System.Nullable`1[System.Int32], System.String, System.DateTime, System.DateTime, TipoResultado)' in 'Imovelweb.Web.Intranet.Controllers.RelatoriosController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
尽管如此,dataInicio
参数仍存在于查询字符串:中
http://localhost:32331/Relatorios/DadosRelatorioResumoLancamentos?codFantasia=106&numAp=&dataInicio=21%2F03%2F2012&dataFim=21%2F03%2F2012&tipoResultado=1
我已经用这两个方法尝试了原始请求(wich返回JSON内容),它可以用POST,但不能用GET(抛出相同的ArgumentException
)。
我错过了什么?
这是Action方法的签名:
public ActionResult DadosRelatorioResumoLancamentos(
int? codFantasia,
string numAp,
DateTime dataInicio,
DateTime dataFim,
TipoResultado tipoResultado = TipoResultado.Json
);
这里是枚举:
public enum TipoResultado
{
Json,
Excel,
Pdf
}
我遇到了这个问题,默认的ASP.NET MVC模型绑定器将QueryString值解析为InvariantCulture
,而POSTed表单值将使用CurrentCulture
进行解析。
这意味着在您的GET请求中,它将尝试以美国格式MM/dd/yyyy解析2012年3月21日,这是无效的。由于dataInicio
参数不可为null,它将无法提供合适的值,因此它将抛出ArgumentException
。
这里有一个完整的总结/解决方法:http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx