WCF Dataservice - modify object before returning results?

柔情痞子 提交于 2019-12-06 02:20:49

IMO this is out of scope of WCF Data Services. WCF Data Services are meant to take your entity model and expose it as is based on access rules. If your entity exposes some properties and that entity is exposed its properties are simply public. It is for simple CRUD scenarios or read-only scenarios.

QueryInterceptor will not help you because it can be used for data driven authorization - it means that QueryInterceptor can add some additional condition to filter records which current user is not permitted to see = it will filter out whole records but it will not modify filtered result.

There is no hook to null fields because that is a bad approach. If you don't want expose some fields they should not be part of exposed entity at all. You can create second read-only entity exposing only public fields by using QueryView in your EDMX file. Next you need to modify access rules in your DataServiceConfiguration. You must remove access rule to initial User entity set and add read access rules to that new entity set.

If you need to control access rules per user you have to use some kind of authentication in your service and you must handle this in InitializeService method (unless DataServiceConfiguration is available elsewhere). Something like:

public static void InitializeService(DataServiceConfiguration config)
{
    var context = ServiceSecurityContext.Current;
    if (context != null && context.PrimaryIdentity != null)
    {
        var userName = context.PrimaryIdentity.Name;
        if (SomeMethodToValidateUserPermissions(userName)
        {
            config.SetEntitySetAccessRule("Users", EntitySetRights.AllRead);
        }
    }

    config.SetEntitySetAccessRule("TrimmedUsers", EntitySetRights.AllRead);
} 

By going more deep into WCF there can be other approaches to restrict access to some resources but this one is simplest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!