NancyFX:如何检查查询字符串/表单值是否已正确传递给我的处理程序? [英] NancyFX: How do I check if query-string / form values have been correctly passed to my handler?
问题描述
Nancy通过dynamic
变量将我的查询字符串和表单值传递给我的处理程序.下面的示例显示了通过Nancy请求将表单值传递给POST处理程序,例如Request.Form.xxx
.
Nancy passes my query-string and form values to my handlers via a dynamic
variable. The example below shows form values being passed in to a POST handler via the Nancy request e.g. Request.Form.xxx
.
处理程序
Post["/"] = _ =>
{
var userId = (string) Request.Form.userid;
if (userId.IsEmpty()) return HttpStatusCode.UnprocessableEntity;
return HttpStatusCode.OK;
};
您可以看到我正在将userid
强制转换为字符串,然后使用字符串扩展方法来检查该值是否为null或空字符串(等同于string.IsNullOrEmpty()
).
You can see that I am casting the userid
to a string and then using a string extension method to check if the value is null or empty string (equivalent to string.IsNullOrEmpty()
).
我希望对动态类型使用扩展方法,这样我就可以在执行其他任何操作之前执行健全性检查.我想要这样的代码:
What I would prefer is to to have the extension method on the dynamic type so I could perform my sanity checks before doing anything else. I want code like this:
if(Request.Form.userid.IsEmpty()) return HttpStatusCode.UnprocessableEntity;
但是,您不能具有dynamic
类型的扩展方法.同样,您不能通过反射检查属性的存在.欢迎使用DLR.
However, you cannot have extension methods for dynamic
types. Also, you cannot check for the presence of a property via reflection. Welcome to the DLR.
问题
执行预检查以确保预期的查询/表单值已传递给我的Nancy处理程序的最简单,最安全的方法是什么?
What is the easiest, safest way to perform pre-checks to ensure that the expected query/form values have been passed to my Nancy handler?
谢谢
推荐答案
Request.Form.userid.HasValue
适用于所有DynamicDictionary成员,例如Form,Query和route参数
Works for all DynamicDictionary members, such as Form, Query and route parameters
这篇关于NancyFX:如何检查查询字符串/表单值是否已正确传递给我的处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!