简体   繁体   English

像WCF REST中的操作筛选器一样?

[英]Something like an operation filter in WCF REST?

I am looking for something like the AuthorizeAttribute in MVC, something I can use like this: 我正在寻找MVC中的AuthorizeAttribute类的东西,可以像这样使用:

    [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));
    }

That WcfAuthorizeAttribute , will try to authenticate the user with FormsAuthentication, and set the context's IPrincipal, or return a HTTP 401 Unauthorized. WcfAuthorizeAttribute ,将尝试使用FormsAuthentication对用户进行身份验证,并设置上下文的IPrincipal或返回未经授权的HTTP 401。

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. 我尝试了IOperationBehavior ,但是无论哪种方法,我都会在第一个方法中执行,而不是在我设置属性的方法中执行。

How can this be achieved in WCF REST? 在WCF REST中如何实现?

Regards. 问候。

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. PS:我已经在入门工具包中看到了RequestInterceptor示例,但是我想要的只是将其放在某些方法中,该示例看起来像是您在所有操作中执行的过滤器。

You can use AOP to achieve this. 您可以使用AOP实现此目的。 I have used PostSharp as an AOP tool to achieve this functionality. 我已将PostSharp用作实现此功能的AOP工具。 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. 在执行方法(使用此属性装饰)之前,将执行OnMethodEntry,然后可以在该方法中执行验证。

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.
    }
}

And you could decorate your WCF methods like below. 您可以如下装饰WCF方法。

[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" } };
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM