【问题标题】:Something like an operation filter in WCF REST?WCF REST 中的操作过滤器之类的东西?
【发布时间】:2011-11-29 23:13:15
【问题描述】:

我正在寻找像 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));
    }

WcfAuthorizeAttribute 将尝试使用 FormsAuthentication 对用户进行身份验证,并设置上下文的 IPrincipal,或者返回 HTTP 401 Unauthorized。

我尝试过使用IOperationBehavior,但我在第一种方法中执行,无论是哪种方法,而不是在我设置属性的方法中。

如何在 WCF REST 中实现这一点?

问候。

PS:我在 Starter Kit 中看到过 RequestInterceptor 示例,但我想要的只是将它放在某些方法中,并且该示例看起来像您在所有操作中执行的过滤器。

【问题讨论】:

    标签: wcf forms-authentication wcf-rest wcf-behaviour


    【解决方案1】:

    您可以使用AOP 来实现此目的。我使用 PostSharp 作为 AOP 工具来实现此功能。您也可以找到sample on their websiteOnMethodEntry 在方法(用此属性修饰)执行之前执行,您可以在那里执行验证。

    我做了一个快速示例来测试它,它有效。

    [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 方法。

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

    【讨论】:

      猜你喜欢
      • 2014-04-08
      • 2018-10-12
      • 2011-08-24
      • 1970-01-01
      • 2012-05-19
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多