验证模型属性 WCF Web APi
我有一组使用 WCF Web Api 托管的服务,我需要做的是验证应用程序模型内的属性。
例如,在 MVC 3 中,我像这样装饰模型中的属性:
[StringLength(30)]
public string UserName { get; set; }
然后在控制器中,我像这样继续验证操作系统,模型是否满足验证参数:
[HttpPost]
ActionResult Create(Model myModel)
{
if(ModelState.IsValid(){
Post the model
}
else
{
Don't post the model
}
}
有没有办法在 WCF Web Api 中执行类似的操作?
I have a set of services hosted with WCF Web Api, what I need to do is validate the properties inside the models of the app.
In MVC 3 for example I decorate properties in the model like this:
[StringLength(30)]
public string UserName { get; set; }
and then in the controller I proceed like this to verify os the model has met the validation parameters:
[HttpPost]
ActionResult Create(Model myModel)
{
if(ModelState.IsValid(){
Post the model
}
else
{
Don't post the model
}
}
Is there a way to do something similar in WCF Web Api?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,我终于成功验证了我的模型的工作情况。我编写了一个验证处理程序和几个扩展方法。首先是验证处理程序:
注意处理程序如何接收 T 对象,这主要是因为我想验证 API 中的所有模型类型。因此,OnGetInputParameters 指定处理程序需要接收 T 类型对象,OnGetOutputParameters 指定处理程序需要返回具有相同 T 类型的对象,以防满足验证策略,如果不满足,请查看 on handler 方法如何抛出异常让客户端知道存在验证问题。
现在我需要注册处理程序,为此我编写了几个扩展方法,遵循 Pedro Felix 博客 http://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/(这个博客帮助了我很多,关于整个处理程序操作的事情有一些很好的解释)。这些是扩展方法:
这个方法检查操作中是否有 T 类型参数,如果有,它将处理程序添加到该特定操作。
该方法调用另一个扩展方法 AddRequestHandler,该方法添加新的处理程序,而不删除以前注册的处理程序(如果存在)。
最后一件事是注册处理程序:
就是这样..希望它对其他人有帮助!
Ok I finally managed to get validations for my models working. I wrote a validation handler and a couple of extensions methods. First thing the validation handler:
Notice how the Handler receives a T object, this is mainly because I would like to validate all the model types within the API. So the OnGetInputParameters specifies that the handler needs to receive a T type object, and the OnGetOutputParameters specifies that the handler needs to return an object with the same T type in case validations policies are met, if not, see how the on handle method throws an exception letting the client know that there's been a validation problem.
Now I need to register the handler, for this I wrote a couple of extensions method, following an example of a Pedro Felix's blog http://pfelix.wordpress.com/2011/09/24/wcf-web-apicustom-parameter-conversion/ (this blog helped me a lot, there are some nice explanations about the whole handler operations thing). So these are the extensions methods:
so this methos checks if there is a T type parameter in the operations, and if so, it adds the handler to that specific operation.
This one calls the other extension method AddRequestHandler, and that method add the new handler without removing the previous registered ones, if the exist.
The last thing is to register the handler:
So this is it.. Hope it helps somebody else!!
我目前正在开发一个 HttpOperationHandler ,它完全可以满足您的需求。现在还没有完成,但是这个伪代码可能会让您了解如何做到这一点。
OnGetInputParameters 值告诉 OnHandle 方法的预期输出,OnGetOutputParameters 告诉 OnHandle 方法的预期输出(稍后将注入到服务中的方法中)。
然后,您可以使用 HttpConfiguration 将处理程序添加到路由,如下所示:
I am currently working on a HttpOperationHandler that does exactly what you need. It's not done by now, but this psuedo code might give you an idea of how you can do it.
The OnGetInputParameters value tells what's expected into the OnHandle method, and the OnGetOutputParameters tells what's the expected output from the OnHandle method (which later on is injected into the method in the service).
You can then add the handler to the routing with a HttpConfiguration as follows:
发布在 MSDN 上有一个创建行为的示例为此,应该有效。您还可以使用 Validator.ValidateObject 手动调用验证器(或将其包装作为扩展方法)并返回验证错误,这本质上就是该行为正在做的事情。
There is an example of this posted on MSDN of creating a behavior for this that should work. You could also call the validators manually with Validator.ValidateObject (or wrap it as an extension method) and return the validation errors, which is essentially what that behavior is doing.
首先,我应该说很棒的问题+答案 Daniel
但是,我已经进一步完善了它并添加了它。
ValidationHander
我对此做了一些改进。它现在基于通用的
HttpOperationHandler
,因此它可以获取HttpRequestMessage
。这样做的原因是我可以返回使用正确媒体类型(来自接受标头)格式化的错误消息。扩展方法
您提供的 2 个方法与在
ModelValidationFor
方法中添加 ValidationHandler 时不再需要的desc
参数几乎保持相同。添加了一个额外的扩展方法。这是为了确保所有“资源”类都经过验证。这主要是我的懒惰和健忘造成的。我永远忘记在某个地方的列表中添加一些类。 (这就是我编写通用 Windsor 安装程序的原因!)
我为
DirectoryCatalog
类使用了System.ComponentModel.Composition.Hosting
命名空间(以前称为 MEF)。在本例中,我只是使用以“Resources”结尾的命名空间来查找我的“Resource”类。将其更改为使用自定义属性或您可能喜欢的任何其他方式来识别哪些类是您的“资源”并不需要太多工作。RestValidationFailure
这是我制作的一个小帮助器类,用于允许验证失败响应的一致行为。
所以,现在我得到了所有验证错误的一个很好的列表(以我喜欢的媒体类型)。
享受! :)
Firstly I should say awesome question+answer Daniel
However, I've taken it a little further, refined it and added to it.
ValidationHander
I've refined this a little. It is now based on a generic
HttpOperationHandler
so it can take theHttpRequestMessage
. The reason for this is so that I can return error messages formatted using the correct media type (from the accept header).Extension Methods
The 2 you provided stay virtually the same about from the
desc
paramter no longer being needed when adding the ValidationHandler in theModelValidationFor
methodI've added an extra extension method. This is to make sure that all "Resource" classes are validated. This is mainly me being lazy and forgetful. I am forever forgetting to add some class to a list somewhere. (It's why I write generic windsor installers!)
I made use of the
System.ComponentModel.Composition.Hosting
namespace (formerly known as MEF) for theDirectoryCatalog
class. In this case I've just used the namespace ending with "Resources" to find my "Resource" classes. It wouldn't take much work to change it to use a custom attribute or whatever other way you might prefer to identify which classes are your "Resources".RestValidationFailure
This is a little helper class I made to allow consistent behaviour for validation failure responses.
So, now I get a nice list (in my preferred mediatype) of all the validation errors.
Enjoy! :)