csharp 自托管ASP.NET Web API的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 自托管ASP.NET Web API的示例相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Threading;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var baseAddress = "http://localhost:8080/";
            var config = new HttpSelfHostConfiguration(baseAddress);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                HttpClientHandler httpClientHandler = new HttpClientHandler();
                httpClientHandler.CookieContainer = new CookieContainer();
                httpClientHandler.CookieContainer.Add(new Cookie("name", "value", "/", "google.de"));

                var client = new HttpClient(httpClientHandler) { BaseAddress = new Uri(/*"http://www.google.de/") }; */ baseAddress) };
                var request = new HttpRequestMessage(HttpMethod.Get, "api/hello");
                Console.WriteLine("Client received: {0}", 
                    client.SendAsync(request).Result.Content.ReadAsStringAsync().Result); // client.GetStringAsync("api/hello").Result);
            }
        }
    }

    public class HelloController : ApiController
    {
        public string Get()
        {
            return "Hello, world!";
        }
    }
}

以上是关于csharp 自托管ASP.NET Web API的示例的主要内容,如果未能解决你的问题,请参考以下文章

请求实体对于自托管 ASP.Net Web API 来说太大

强大的自托管服务器的最佳选择:WCF 与 ASP.NET Web Api

csharp Nancy和ASP.NET Web API比较

csharp 在ASP.NET Web Api有效负载中添加资源链接

如何在 asp.net 自托管 API 中启用 CORS?

csharp ASP.NET Web API:通过提供自己的AssembliesResolver来控制加载的程序集