上一个自主托管Web Api 的示例存储一些问题,如下Self Host Web Api 测试OK。
1. 创建 ConsoleApp
定义项目名称: SefHostWebApiSample
2. 添加第三方组件
Microsoft.AspNet.WebApi.SelfHost
Microsoft.Net.Http
Newtonsoft.Json
3. 创建Controller 类 ,ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SefHostWebApiSample
{
public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2", "value3" }; } // GET api/values/5 public string Get(int id) { return "value" +id; } // POST api/values public void Post([FromBody] string value) { } // PUT api/values/5 public void Put(int id,[FromBody] string value) { } // DELETE api/values/5 public void Delete(int id) { } }
}
4. Program.cs 中添加SelfHost代码
using System.Web.Http.SelfHost;
using System.Web.Http;
namespace SefHostWebApiSample
{
class Program { static void Main(string[] args) { Uri myUri = new Uri(@"http://localhost:9999"); // Let have our configurations readY HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(myUri); // configure routes config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); HttpSelfHostServer server = new HttpSelfHostServer(config); // Start listening server.OpenAsync().Wait(); Console.WriteLine("WebApi hosted on " + myUri.AbsoluteUri + " It can be tested now"); Console.ReadLine(); } }
}
5. 运行App
App显示如下信息:
WebApi hosted on http://localhost:9999/ It can be tested now
在浏览器上输入:http://localhost:9999/api/values
This XML file does not appear to have any style information associated with it. The document tree is shown below.
value1
value2
value3
在浏览器上输入:http://localhost:9999/api/values/5
This XML file does not appear to have any style information associated with it. The document tree is shown
value5
测试OK !