在控制台而不是网页中显示结果

时间:2018-02-01 03:08:53

标签: c# asp.net

我创建的项目是一个ASP.NET Web API,它通过HttpClient与Java Web Service进行通信。当我运行Java Web Service时,我得到结果{"id":2,"content":"Hello, World!"}。当我运行ASP.NET Web API时,ASP.NET Web API从Java Web Service获取结果,并在网页中显示结果"{\"id\":2,\"content\":\"Hello, World!\"}"

如何在控制台中显示结果,这意味着我创建了一个控制台应用程序并输入这些代码,我希望结果出现在控制台而不是网页中。我怎么做?有哪些代码需要修改?请有人帮我谢谢你。

以下是我迄今为止所做的ASP.NET代码:

ClientController.cs

public class ClientController : ApiController
{
    private ServerClient serverClient = new ServerClient();

    public async Task<IHttpActionResult> GET()
    {
        try
        {
            var result = await serverClient.content();
            return Ok(result);
        }

        catch (Exception e)
        {
            var result = "Server is not running";
            return Ok(new { ErrorMessage = result });
        }
    }
}

ServerClient.cs

public class ServerClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static ServerClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> content()
    {
        var endpoint = string.Format("greeting");
        var response = await client.GetAsync(endpoint);
        return await response.Content.ReadAsStringAsync();
    }
}

WebApiConfig.cs

config.Routes.MapHttpRoute(
        name: "TestClient",
        routeTemplate: "api/testclient",
        defaults: new { actcion = "Get", controller = "Client" }
        );

1 个答案:

答案 0 :(得分:2)

static void Main(string[] args)
{
    var result = serverClient.content().Result;
    Console.WriteLine(result);
}

请注意,在Result编程中使用Wait()async可能会导致死锁