سؤال

I have a scenario where I need to send the user to the login page, with the returnurl parameter populated with the page they're currently sitting on including a url fragment, so as when they complete login, they're redirected back to their original page and the page scrolls down to a specific #location.

At present, it's all working except that the url fragment is lost when the returnUrl param reaches the Login ActionMethod.

Is there a way to retain this url fragment so it doesn't get lost during the login phase? I can see the #fragment in the url on the login page, but it appears to be stripped off when I look at the value of 'returnUrl' in my login method.

هل كانت مفيدة؟

المحلول

Is there a way to retain this url fragment so it doesn't get lost during the login phase?

No, there isn't. The url fragment is never sent to the server. One possibility is to modify the returnUrl on the client before passing it to the server so that the url fragment becomes part of the query string. Then when the login succeeds and the server needs to redirect back to the returnUrl it would modify it to the original value.

For example it might look like this before sending it to the Login method:

http://example.com/admin/index?fragment=somefragment

نصائح أخرى

If your redirected login url looks like this https://example.com/Login?ReturnUrl=%2F#/protected/page, anything to the right of the hash(#) never gets passed to the server. If you inspect your form, you will see the form action omits the hash fragment.

<form action="/Login?ReturnUrl=%2F" id="login-form" method="post" role="form">
           ....
</form>

Notice the missing fragment in form action. The way I solve this is by capturing the hash fragment from the url and adding it back to the form action through javascript. Right below the login form, I have this inline script:

<script type="text/javascript">
    window.onload = function () {
        var hash = window.location.hash.substr(1);
        if (hash !== "") {
            var form = document.getElementById('login-form');
            var action = form.getAttribute("action") + 'NHASH' + encodeURIComponent(hash);
            form.setAttribute("action", action);
        }
    }
</script>

So now the form action will look like this action="/Login?ReturnUrl=%2FNHASH%2Fprotected%2Fpage". On the server side, after successful authentication and before redirecting to the ReturnUrl, you replace the NHASH with # such as

returnUrl = returnUrl.Replace("NHASH", "#");

Note: You can use any token for #. I just chose NHASH

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top