简体   繁体   中英

Calling variable from web.config to code behind

I would like to call a "variable" from the web.config to the code behind then a button is clicked and I want the user to be redirected to the link that is on that vaiable. I tried it this way:

web.config:

<appSettings>
    <add key ="E-leg" value ="https://google.com"/>
</appSettings>

Code behind(on button click:

    Protected Sub ELegLogin(sender As Object, e As EventArgs)

        Dim str As string  = ConfigurationManager.AppSettings["E-leg"].ToString();

'Error: Identifier expected

        Response.Redirect(Str)

'Argument not specified for parameter 'Number' of 'Public Function Str(Number As Object) As String
    End Sub
End Class

This doesn't work. I get error " Identifier expected " and " Argument not specified for parameter 'Number' of 'Public Function Str(Number As Object) As String "

I would appreciate it if someone could help me out

You could try AppSettingsReader .

web.config:

<appSettings>
    <add key ="E-leg" value ="https://google.com"/>
</appSettings>

code:

Dim reader As New System.Configuration.AppSettingsReader
Response.Redirect(reader.GetValue("E-leg", GetType(String)))

See more options here .

You have a variable called str and a function called Str . VB.NET is a case sensitive language. If you want to redirect to the location represented by str , then make sure you pass that variable to your Response.Redirect call.

Protected Sub ELegLogin(sender As Object, e As EventArgs)
        Dim str As string  = ConfigurationManager.AppSettings["E-leg"].ToString();
        Response.Redirect(str)
End Sub

Note that it's never a good idea to name your variable str as it's not clear what it represents. Always give your variables a more semantic name, such as eLegRedirectUrl . And also, avoid having two options with similar names, such as a variable named str and a function named Str .

If we assume your web.config looks something like this:

<appSettings>    
     <add key="ClientId" value="234234234"/>    
     <add key ="RedirectUrl" value="http://stackoverflow.com"/>
  </appSettings>

Then you could add the namespace

using System.Configuration;

Then:

string Clientid = ConfigurationManager.AppSettings["ClientId"].ToString();
string Redircturl = ConfigurationManager.AppSettings["RedirectUrl"].ToString();

And you are good to go.

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