简体   繁体   中英

React.js Get logged in user in asp.net application

I am converting from C# views to using react. I want to render some html depending on whether the user is authenticated or not, in C# this was as easy as this:

    <ul class="outer pull-right">
        @if (User.Identity.IsAuthenticated)
        {
            <li>    
                <form action="logout" id="logout-form">
                    <input type="submit" value="Logout" />
                </form>
            </li>
        }
    </ul>

What is the correct way to do this in react.js? Pseudocode For example:

export default class Nav extends React.Component {
    getCurrentUser(){
        //Use ajax to get current user from server?
    }
    render(){
        return (
            <ul class="outer pull-right">
                @if (User.Identity.IsAuthenticated) 
                {
                    <li>    
                        <form action="logout" id="logout-form">
                            <input type="submit" value="Logout" />
                        </form>
                    </li>
                }
            </ul>
        );
    }
}

If you're going to use c# sessions in your react application, you'll need an API call. For obvious reasons, you'll be using react-router. And for that, people generally adopt this method to authenticate user.

Agreed, that it is not that easy to authenticate the user. But once you've set up the mechanism, you won't need to look back again.

Good luck!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM