Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpActionResult method cannot return NotFound()

I am developing a web API for my website and have ran into a problem.

At the moment, the API is supposed to return details from the specified user.

This is my controller for accounts:

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);
        }

    }
}

Although most of this code is copied from the tutorial here, Visual Studio complains that 'NotFound()' and 'Ok(account)' do not exist in the current context. I have updated all of the NuGet packages to version 5.1.2+ and I still get this error.

I have done some research and found that it seems to work for other people...

I would much appreciate it if anyone could respond with a working solution! Thank you.

like image 933
rodit Avatar asked May 30 '14 13:05

rodit


People also ask

What is the namespace for IHttpActionResult return type in Web API?

The IHttpActionResult interface is contained in the System. Web. Http namespace and creates an instance of HttpResponseMessage asynchronously. The IHttpActionResult comprises a collection of custom in-built responses that include: Ok, BadRequest, Exception, Conflict, Redirect, NotFound, and Unauthorized.

What is the difference between IHttpActionResult and Actionresult?

What is the difference between IHttpActionResult and IActionresult ? "IActionResult is the new abstraction that should be used in your actions. Since Web API and MVC frameworks have been unified in ASP.NET Core, various IActionResult implementations can handle both traditional API scenarios.".

What is IHttpActionResult C#?

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface: Simplifies unit testing your controllers. Moves common logic for creating HTTP responses into separate classes.


1 Answers

You need to inherit your controller from ApiConroller - that is where these methods are defined:

public class AccountController : ApiController
like image 198
Andrei Avatar answered Oct 07 '22 20:10

Andrei