从asp.net应用程序调用webapi作为客户端

时间:2015-08-08 13:56:45

标签: asp.net-web-api

我有一个带有返回字符串值的方法的web api。我在Web应用程序中有这个web api控制器。我试图使用以下代码调用api中的方法:

        Stream data = client.OpenRead(new Uri("http://localhost:40786/api/Getvalues/getstring"));
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
        data.Close();
        reader.Close();

我在网页的点击事件上调用此方法说Default.aspx。代码运行正常,但不是调用web-api并返回它的值,它返回我有按钮的页面的HTML标记。不知道发生了什么。谁能提出我在这里缺少的东西?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

internal class Program
{
    private static DateTime? _nullableDateTime;

    private static void Main( string[] args )
    {
        // Use the debugger to step through this repro. 
        // * Not sure if it matters, but I started with F11 right from the         start without any breakpoints.
        // ==============================================================================================

        // 1. Variable starts off with default of null
        //    The following statement will confirm that with an "empty" value in the console window
        Console.WriteLine( _nullableDateTime );

        // 2. The next statement assigns the current date and time
        _nullableDateTime = DateTime.Now;

        // 3. The following statement will confirm the correct value in the console window
        Console.WriteLine( _nullableDateTime );

        // 4. THIS IS WHERE THE TROUBLE STARTS
        //    Now, using the immediate window, change the value of the variable with the 
        //    following statement (after the colon) : _nullableDateTime = DateTime.Now
        //    
        //  
        //

        // 5. After changing the value via the immediate window, let's look at it's value now.
        //    For me (as can be seen in the video), I get the completely wrong value in the console window.
        Console.WriteLine( _nullableDateTime );
    }
}