[英]How do I return NotFound() IHttpActionResult with an error message or exception?
[英]IHttpActionResult method cannot return NotFound()
我正在为我的网站开发 web API 并且遇到了问题。
目前,API 应该返回指定用户的详细信息。
这是我的 controller 帐户:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using System.Net;
using RoditRepoAPIV2.Models;
namespace RoditRepoAPIV2.Controllers
{
public class AccountController : Controller
{
Account[] products = new Account[]
{
//accounts will be added...
};
public IEnumerable<Account> GetAllAccounts()
{
return products;
}
public IHttpActionResult GetAccount(int id)
{
var account = products.FirstOrDefault((p) => p.Id == id);
if (account == null)
{
return NotFound();
}
return Ok(account);
}
}
}
尽管大部分代码都是从教程复制而来,Visual Studio 抱怨当前上下文中不存在“ NotFound()
”和“ Ok(account)
”。 我已将所有NuGet 软件包更新到版本 5.1.2+,但仍然出现此错误。
我做了一些研究,发现它似乎对其他人有用......
如果有人能用可行的解决方案做出回应,我将不胜感激。 谢谢你。
您需要从ApiConroller
继承您的控制器 - 这是定义这些方法的地方:
public class AccountController : ApiController
从 aspnet 核心 6
代替
return NotFound() and HttpNotFound();
和
return new StatusCodeResult(404);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.