示例代码链接:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
在新建webapicontroller时,如下:
internal class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> 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)
{
}
}
运行程序时发现结果如下,与示例程序不符:
写入HttpResponseMessage对象
StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Tue, 29 May 2018 07:05:52 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 185
Content-Type: application/json; charset=utf-8
}
写入序列化对象
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:9000/api/values'.","MessageDetail":"No type was found that matches the controller named 'values'."}
写入完成
排错过程:
由返回状态码404可知,方法未找到,检查路由,未发现问题,遂查看控制器类的可访问性,发现其为internal,改为public后再次运行,结果正常。
由于VS在新建类时,默认为其添加internal修饰符,而这对于apicontroller派生类是不合适的,应加以注意。
附链接:
不使用OWin的自寄宿:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/self-host-a-web-api