用以下内容替换此文件中的所有样板代码:
复制代码
using Owin;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
复制代码
添加Web API控制器
接下来,添加一个Web API控制器类。在解决方案资源管理器中,右键单击该项目,然后选择“ 添加 / 类”以添加新的类。给班级命名ValuesController。
用以下内容替换此文件中的所有样板代码:
复制代码
using System.Collections.Generic;
using System.Web.Http;
namespace OwinSelfhostSample
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable Get()
{
return new string[] { “value1”, “value2” };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// 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)
{
}
}
}
复制代码
启动OWIN主机并向HttpClient发出请求
用以下内容替换Program.cs文件中的所有样板代码:
复制代码
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
namespace OwinSelfhostSample
{
public class Program
{
static void Main()
{
string baseAddress = “http://localhost:9000/”;
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpClient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
}
}
复制代码
运行应用程序
若要运行该应用程序,请在Visual Studio中按F5。输出应如下所示:
复制代码
StatusCode: 200, ReasonPhrase: ‘OK’, Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Mon, 04 May 2020 07:35:10 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 19
Content-Type: application/json; charset=utf-8
}
[“value1”,“value2”]
亚马逊测评 www.yisuping.com