Home > Net >  Optimize repeatable anonymous delegates C#
Optimize repeatable anonymous delegates C#

Time:07-22

I register policies for authorization. Claim options it's array of abilities users on site ['cm', 'wtm', 'um']. With the help of RequireAssertion check availability required ability. How I can optimize this repeatable code? Thank you!

    policyBuilder.AddPolicy("UmPolicy", policy =>
    {
        policy.RequireAssertion(context =>
        {
            var optionsSerializedArray = context.User.FindFirstValue(ClaimType.Options);

            if (optionsSerializedArray == null)
            {
                return false;
            }

            var deserializedOptionsUser = JsonSerializer.Deserialize<string[]>(optionsSerializedArray);
            var option = deserializedOptionsUser?.SingleOrDefault(value => value == "um");

            return option != null;
        });
    });

    policyBuilder.AddPolicy("CmPolicy", policy =>
    {
        policy.RequireAssertion(context =>
        {
            var optionsSerializedArray = context.User.FindFirstValue(ClaimType.Options);

            if (optionsSerializedArray == null)
            {
                return false;
            }

            var deserializedOptionsUser = JsonSerializer.Deserialize<string[]>(optionsSerializedArray);
            var option = deserializedOptionsUser?.SingleOrDefault(value => value == "cm");

            return option != null;
        });

        policyBuilder.AddPolicy("WtmPolicy", policy =>
        {
            policy.RequireAssertion(context =>
            {
                var optionsSerializedArray = context.User.FindFirstValue(ClaimType.Options);

                if (optionsSerializedArray == null)
                {
                    return false;
                }

                var deserializedOptionsUser = JsonSerializer.Deserialize<string[]>(optionsSerializedArray);
                var option = deserializedOptionsUser?.SingleOrDefault(value => value == "wtm");

                return option != null;
            });
        });

CodePudding user response:

You can use a Dictionary to store all policy names and write the code in a loop over dictionary items.

Dictionary<string, string> policies = new() { { "UmPolicy", "um" }, { "CmPolicy", "cm" }, { "WtmPolicy", "wtm" } };

foreach(var item in policies)
{
    policyBuilder.AddPolicy(item.Key, policy =>
    {
        policy.RequireAssertion(context =>
        {
            var optionsSerializedArray = context.User.FindFirstValue(ClaimType.Options);

            if (optionsSerializedArray == null)
            {
                return false;
            }

            var deserializedOptionsUser = JsonSerializer.Deserialize<string[]>(optionsSerializedArray);
            var option = deserializedOptionsUser?.SingleOrDefault(value => value == item.Value);

            return option != null;
        });
    });
}
  • Related