简体   繁体   中英

How do I get the username and password from a URL

用户名和密码来自如下网址:

https://theuser:thepassword@localhost:20694/WebApp

Create a Uri and then get the UserInfo property:

var uri = new Uri("https://theuser:thepassword@localhost:20694/WebApp");
Console.WriteLine(uri.UserInfo); // theuser:thepassword

If necessary you can then split on : , like this:

var uri = new Uri("https://theuser:thepassword@localhost:20694/WebApp");
var userInfo = uri.UserInfo.Split(':');
Console.WriteLine(userInfo[0]); // theuser
Console.WriteLine(userInfo[1]); // thepassword

Note that if you're trying to get the current user in the context of an ASP.NET request, it's better to use the provided APIs, like HttpContext.User :

var userName = HttpContext.Current.User.Identity.Name;

Or if this is in a web form, just:

protected void Page_Load(object sender, EventArgs e)
{
    Page.Title = "Home page for " + User.Identity.Name;
    }
    else
    {
        Page.Title = "Home page for guest user.";
    }
}

As for passwords, I'd recommend you not trying to deal with the passwords directly after the user has been authenticated.

var str = @"https://theuser:thepassword@localhost:20694/WebApp";
var strsplit = str.Split(new char[] {':', '@', '/'};
var user = strsplit[1];
var password = strsplit[2];

You can get the current uri with the following approach

string uri = HttpContext.Current.Request.Url.AbsoluteUri; //as u targeted .net

Then parse it as a normal string.

You'll receive the following string : https://theuser:thepassword@localhost:20694/WebApp

And you can get the information you are searching for by splitting the string into pieces.

        var uri = "https://theuser:thepassword@localhost:20694/WebApp";
        var currentUriSplit = uri.Split(new [] { ':', '@', '/' });
        var user = currentUriSplit[3];
        var password = currentUriSplit[4];

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