开发者

Call function who's name is stored in a variable

I have created a small classic asp file t开发者_运维百科hat I indend to call form asp.net using the below. I works, but it feels wrong somehow:

Booking.BelongsToSite = file_get_contents("http://localhost:82/test2.asp?functionName=RetBTS&param=" + User.ID);

protected string file_get_contents(string fileName)
{
    string sContents = string.Empty;
    if (fileName.ToLower().IndexOf("http:") > -1)
    { // URL 
        System.Net.WebClient wc = new System.Net.WebClient();
        byte[] response = wc.DownloadData(fileName);
        sContents = System.Text.Encoding.ASCII.GetString(response);
    }
        else
        {
            // Regular Filename 
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            sContents = sr.ReadToEnd();
            sr.Close();
        }  
        return sContents;
    }

Can anyone see any problems with doing this?

Also is it possible to do something like the below in Classic ASP / VB script. I can't get it to call a dynamic function name:

dim functionName, param, result
functionName = request("functionName")
param = request("param")

result = functionName(param)

Also any idea how to parse the parameters. Say if I pass the parameters in the head like "1,2,3,4", how can I pass the into the parenthesis?


I think you're looking for the Eval function in VBScript. You can use it to call your method in the following way (demo script is vbs in wsh):

Dim func, param

func = "Hello"
param = "everybody"

MsgBox(Eval(func & "(""" & param & """)"))

Function Hello(name)
Hello = "Hello " & name
End Function

That returns "Hello everybody", as expected.

As for your asp.net code: I'm not going to judge whether or not your solution is sensible, I don't know the situation. It can definitely work though. Just two remarks:

  1. Both WebClient and StreamReader implement IDisposable. Wrap them in a using block.
  2. If you're going to download urls like that, make sure to validate your string, so that you don't go and download bad urls. Same for the function name in your classic asp that you pass in your querystring.

Menno


Try to use GetRef instead of Eval.

dim functionName, param, result
functionName = request("functionName")
param = request("param")

result = GetRef(functionName)(param)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜