Method not found in Web API 2

I am trying to figure out how to use the web API. I went through some tutorials and now I am trying to set up my webservice. It is very difficult for me to try to understand why he cannot find my methods. It just seems random to me (the tutorials worked great). During my experimentation, the get method returns "no method allowed".

This is my service:

public class ContentFilesController : ApiController
{
  [Route("api/contentfile/{id}")]
    [HttpGet]
    public IHttpActionResult GetContentFiles(int count)
    {
        if (_contentFiles == null)
            GenerateContentFileList();
        List<ContentFile> files = new List<ContentFile>();
        int i = 0;
        while(true)
        {
            ContentFile cf = _contentFiles[i];
            if(!_filesOutForProcessing.Contains(cf))
            {
                files.Add(cf);
                i++;
            }
            if (i == count)
                break;
        }
        return Ok(files);
    }
    [HttpPost]
    [Route("api/contentfile/{files}")]
    public IHttpActionResult Post([FromBody] List<ContentFile> files)
    {
        return Ok();
    }

      

}

Edit: This is the code I'm using to call the service:

static async Task TestAsync()        {
        using (var client = new HttpClient())            {
            client.BaseAddress = new Uri("http://localhost:46015/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await client.GetAsync("api/contentfile/1");
            if (response.IsSuccessStatusCode)
            {
                var contentfiles = await response.Content.ReadAsAsync<List<ContentFile>>();                    
            }
        }
    }

    static async Task ReportTest()
    {
        List<ContentFile> files = new List<ContentFile>()
        {
            new ContentFile(){Path="hej"},
            new ContentFile(){Path="dΓ₯"}
        };

        using(var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:46015");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await client.PostAsJsonAsync<List<ContentFile>>("api/contentfile", files);
            if(response.IsSuccessStatusCode)
            {

            }
        }
    }

      

Where to begin? This is where I'm going crazy.

Thank!

Edit: To clarify the error, the problem with both client methods is that HttpResponseMessage has response.IsSuccessStatusCode false and StatusCode = MethodNotAllowed or MethodNotFound.

+3


source to share


1 answer


GET method problems

There is a problem with your routing for the HTTP Get method.

You have declared a GET route like this:

[Route("api/contentfile/{id}")]

      

but then the method parameter is declared like this:

 public IHttpActionResult GetContentFiles(int count)

      

When using attribute-based routing, the parameter names must match.

I made a very simple reproduction of your code (obviously I don't have your classes, but the infrastructure will be the same)

In a WebAPI project

public class ContentFile
    {
        public int ID { get; set; }
    }

    public class ContentFilesController : ApiController
    {
        [Route("api/contentfile/{count}")] //this one works
        [Route("api/contentfile/{id}")] //this one does not work
        [HttpGet]
        public IHttpActionResult GetContentFiles(int count)
        {
            var files = new List<ContentFile>();
            for (int x = 0; x < count; x++)
            {
                files.Add(new ContentFile(){ID=x});
            }

            return Ok(files);
        }
    }

      



In a client project

public class ContentFile
    {
        public int ID { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:51518/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("api/contentfile/1").Result;
                var data = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(data);
                Console.ReadKey();
            }
        }
    }

      

Thus, the code is not exactly identical to yours, but it is almost the same code. Running a WebAPI project and then the client gives me:

[{"ID":0}]

Problems with the POST method

In the case of a method, POST

you declare a route parameter, but this is never sent as part of the route, this is the POST body:

[HttpPost]
[Route("api/contentfile/{files}")] //{files} here tells routing to look for a parameter in the *Route* e.g api/contentfile/something
public IHttpActionResult Post([FromBody] List<ContentFile> files)

      

So, a simple fix is ​​to remove {files}

from the route template for this.

Hope it helps.

+5


source







All Articles