像WCF REST中的操作筛选器一样? [英] Something like an operation filter in WCF REST?
问题描述
我正在寻找MVC中的AuthorizeAttribute
之类的东西,我可以这样使用:
I am looking for something like the AuthorizeAttribute
in MVC, something I can use like this:
[WebGet(UriTemplate = "data/{spageNumber}")]
[WebCache(CacheProfileName = "SampleProfile")]
[WcfAuthorize]
public IEnumerable<SampleItem> GetCollection(String spageNumber)
{
Int32 itemsPerPage = 10;
Int32 pageNumber = Int32.Parse(spageNumber);
return Enumerable.Range(pageNumber * itemsPerPage, itemsPerPage)
.Select(i => SampleItem.Create(i));
}
该WcfAuthorizeAttribute
将尝试使用FormsAuthentication对用户进行身份验证,并设置上下文的IPrincipal,或返回未经授权的HTTP 401.
That WcfAuthorizeAttribute
, will try to authenticate the user with FormsAuthentication, and set the context's IPrincipal, or return a HTTP 401 Unauthorized.
我尝试过使用IOperationBehavior
,但是无论哪种方法,我都会在第一个方法中执行,而不是在我设置属性的方法中执行.
I have tried with a IOperationBehavior
, but I gets executed in the first method, whichever it be, not in the method I have set the attribute.
如何在WCF REST中实现?
How can this be achieved in WCF REST?
致谢.
PS:我已经在入门工具包中看到了RequestInterceptor示例,但是我想要的只是将其放在某些方法中,该示例看起来像是您在所有操作中执行的过滤器.
PS: I have seen the RequestInterceptor example in the Starter Kit, but what I want is put it in some methods only, and the example looks like a filter you execute in all the operations.
推荐答案
您可以使用 AOP 一个>实现这一目标.我已经使用 PostSharp 作为实现此功能的AOP工具.您还可以在其网站上找到示例. OnMethodEntry 在执行方法(用此属性修饰)之前执行,您可以在此处执行验证.
You can use AOP to achieve this. I have used PostSharp as an AOP tool to achieve this functionality. You can also find a sample on their website. The OnMethodEntry gets executed before a method (that is decorated with this attribute) is executed and you can perform your validation there.
我做了一个简短的示例来测试这一点,并且它起作用了.
I did a quick sample to test this and it worked.
[Serializable]
[ProvideAspectRole(StandardRoles.Security)]
public class WcfAuthorizeAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
//extract forms authentication token here from the request and perform validation.
}
}
您可以如下装饰WCF方法.
And you could decorate your WCF methods like below.
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
[WcfAuthorize]
[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()
{
return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
}
这篇关于像WCF REST中的操作筛选器一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!