I want to print a variable on the screen using Razor. I have a class named CustomPrincipal saved in the HttpContext, which is saved correctly.
I want it to have it on one line like the example below, which is unfortunately not working:
@* This is not working... *@
@(CustomPrincipal)Context.Items["IUser"].Name
The example below is working though, so it saved it correctly to the HttpContext.
@{ CustomPrincipal user = (CustomPrincipal)Context.Items["IUser"]; }
@user.Name
Does anyone know why the first example is not working and can you show me a solution?
The error is:
Compiler Error Message: CS0118: 'CustomPrincipal' is a 'type' but is used like a 'variable'
All the credits go to @DavidG and @CodeCaster, mentioned in the comments.
@(((CustomPrincipal)Context.Items["IUser"]).Name)
The parentheses where required because otherwise there is no Name
property on the Object
type which is what Context.Items["IUser"]
is. We have to add parentheses to cast that Object
to CustomPrincipal
first, then access the Name
property of that type.
Another example of the same problem: https://stackoverflow.com/a/4151988/4585226
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.