Home > Mobile >  Blazor: how can I restrict access to a property in a razor file (razor component)?
Blazor: how can I restrict access to a property in a razor file (razor component)?

Time:01-31

I have a razor file:

<div>@GetEmail()</div>

And a code behind file:

public partial class EmailAddress
{
    [Inject]
    private IOptionsSnapshot<EmailSettings> EmailSettings { get; set; }

    private string GetEmail()
    {
        return EmailSettings.Value.EmailAddress;
    }
}

I am injecting "EmailSettings" (there are: EmailAddress, EmailLogin or EmailPassword). Now a frontend developer can use in the razor file the following code (but I don't want it), he should use only "GetEmail" method:

@EmailSettings.Value.EmailAddress
@EmailSettings.Value.EmailLogin
@EmailSettings.Value.EmailPassword

But it shouldn't be allowed in the razor file (only allowed in the code behind file). How can I do that?

CodePudding user response:

But it shouldn't be allowed in the razor file (only allowed in the code behind file).

That can't be done.

The .razor file and the code-behind file hold 2 sections of the same partial class. During compilation they will be merged into 1 class, in IL the distinction is no longer present.

Also, be aware that concepts like public and private are not about security but about organizing your code (architecture).

Now a frontend developer can use in the razor file

When you want to prevent that then you will have to split the EmailSettings into two or three different classes. But the code-behind code will see the same restrictions, that can't be helped.

  •  Tags:  
  • Related