C# input on Layout page using Web API

2019-09-21 11:31发布

问题:

I've written the following code in Console. I want to display the string the code returns, on my Layout.cshtml page like any other things on the page. How can I do it using Web API?

 namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string serverName = "localhost";

            var nsm = new ServerManager();

            using (Microsoft.Web.Administration.ServerManager sm = Microsoft.Web.Administration.ServerManager.OpenRemote(serverName))
            {

               //site mySite = sm.Sites.Add("Racing Cars Site", d:\\inetpub\\wwwroot\racing",  8080);
                int counter = 1; 
                foreach (var site in sm.Sites)
                {
                    //var p = site.Bindings.GetCollection().GetAttribute("physicalPath");
                    var p = site.Applications[0].VirtualDirectories[0].PhysicalPath;
                      int b=0;

                    foreach (Microsoft.Web.Administration.Binding binding in site.Bindings)
                         b= binding.EndPoint.Port;

                    Console.Write(String.Format(CultureInfo.InvariantCulture
                        , "Site number {0} : , {1} PhysicalPath : {2}  , Port:{3} {4} "
                        , counter.ToString(), site.Name ,p , b, Environment.NewLine));
                    counter++; 
                }
                Console.ReadKey();

            }
        }

    }
}

回答1:

If you want these codes in MVC you need to create MVC application. No other way to do it, in that case.

Try to rewrite that in MVC. By the way if you want to show the output in the console application you must use Debug for that.

Here is the example :

System.Diagnostics.Debug.WriteLine("The String");

So it means debug is the console code in MVC.

Update : If you want to show the result of your codes in web pages you have to rewrite your codes in MVC application.

You also asked if you want to use helpers, so I should say you can definitely use MVC helpers.

Hope it helps.



回答2:

Your need is not related to Web API, forget about this. An ASP.NET MVC application is the way to go. As you said, it can be done using a helper but it exists easier ways to do that. (Using model or Viewbag). You will also need to learn how to use the markup of the rendering engine used in your view, like Razor. I suggest you to read some tutorials, starting from here for your issue, and here