在ASP.net中通过C#进行套接字编程

时间:2010-11-15 17:09:51

标签: c# asp.net perl

这可能是在ASP.net中用C#写一个Socket吗? 例如我可以在C#和asp.net中编写类似Perl代码的代码吗? :

> use HTTP::Request::Common qw(POST);
> use LWP::UserAgent; $ua = new
> LWP::UserAgent(agent => 'Mozilla/5.0(Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5)Gecko/20060719 Firefox/1.5.0.5'); 
> $ua -> timeout(20);
> my $req = POST 'http://Example.com/',
> [ login_username => 'mehdi' , login22 => '654321' , go => 'submit']; 
> my $content = $ua->request($req);

请给我一个例子或将上面的代码转换为C#和asp.net。 提前致谢 。

1 个答案:

答案 0 :(得分:6)

是的,您可以使用WebClient类在.NET中实现相同的功能:

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0(Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5)Gecko/20060719 Firefox/1.5.0.5";
            var values = new NameValueCollection
            {
                { "login_username", "mehdi" },
                { "login22", "654321" },
                { "go", "submit" }
            };
            var result = client.UploadValues("http://example.com", values);

            // TODO: handle the result here like
            Console.WriteLine(Encoding.Default.GetString(result));
        }
    }
}