我正在使用.net Framework 4.5.2和asp.net Web API。
我创建了一个名为LoginVerification的新控制器,当我运行该应用程序时,我在api标签下看不到该控制器。另外,当我尝试通过转到http://localhost:51449/api/LoginVerification在Postman中进行获取或发布时,出现以下错误:
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:51449/api/LoginVerification'.",
"MessageDetail": "No type was found that matches the controller named 'LoginVerification'."
我不确定为什么无法导航到LoginVerification Controller。
[Authorize]
[RoutePrefix("api/LoginVerification")]
public class LoginVerificationController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public HttpResponseMessage Post([FromBody]string value)
{
string retVal = string.Empty;
LoginModel loginModel = new LoginModel();
retVal = loginModel.VerifyLoginValue(value);
return new HttpResponseMessage()
{
Content = new StringContent(retVal, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.OK
};
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
答案 0 :(得分:0)
您在Route
操作上缺少ApiController
属性。通过使用RoutePrefix
,您可以告诉路由表该控制器正在使用属性路由,因此操作也需要属性
[Authorize]
[RoutePrefix("api/LoginVerification")]
public class LoginVerificationController : ApiController {
// GET api/<controller>
[HttpGet]
[Route("")]
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
[HttpGet]
[Route("{id:int}")]
public string Get(int id) {
return "value";
}
// POST api/<controller>
[HttpPost]
[Route("")]
public HttpResponseMessage Post([FromBody]string value) {
//...
}
// PUT api/<controller>/5
[HttpPut]
[Route("{id:int}"]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
[HttpDelete]
[Route("{id:int}"]
public void Delete(int id)
{
}
}
最后确保在WebApiConfig
中启用属性路由
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}