简体   繁体   中英

MVC Controller unable to find Api Controller (same project)

(Sorry if my english sucks a little)

I'm trying to call an api method from a mvc controller but the mvc seems unable to find the method. I set the route in the mvc controller as

[Route("[controller]")]

and in the api controller as

[Route("api/[controller]")]

In the startup.cs file i added this command to enable default route

app.UseMvcWithDefaultRoute();

Mvc controller code:

[HttpGet]
    public async Task<ActionResult> GetAll()
    {
        IEnumerable<Utente> utenti = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:57279/");
            var Res = await client.GetAsync("api/utente/GetAll");

            if (Res.IsSuccessStatusCode)
            {
                var readTask = Res.Content.ReadAsAsync<IList<Utente>>();
                utenti = readTask.Result;
            }
            else
            {
                utenti = Enumerable.Empty<Utente>();

                ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
            }
        }
        return View(utenti);
    }

Api code:

[HttpGet]
    public IHttpActionResult GetAll()
    {
        IList<Utente> utenti = null;

        using (_utenteContext)
        {
            utenti = _utenteContext.Utenti.Select(u => new Utente()
                        {
                            id = u.id,
                            user = u.user,
                            password = u.password
                        }).ToList<Utente>();
        }

        if (utenti.Count == 0)
        {
            return NotFound();
        }

        return Ok(utenti);
    }

The problem might be that I'm following an old example for both mvc and api controllers in same project, but I'd like if you guys could help me with it.

In the:

var Res = await client.GetAsync("api/utente/GetAll");

I always get {StatusCode: 404, ReasonPhrase: 'Not Found',...} no matter the changes I make to the code.

EDIT:

Whole Api Controller (I was trying also with a POST method but it doesn't work either)

using AdrianWebApi.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace AdrianWebApi.Controllers.api
{
[Route("api/[controller]")]
public class UtenteController : ApiController
{
    private readonly UtenteContext _utenteContext;

    public UtenteController(UtenteContext context)
    {
        _utenteContext = context;
    }

    [HttpGet]
    public IHttpActionResult GetAll()
    {
        IList<Utente> utenti = null;

        using (_utenteContext)
        {
            utenti = _utenteContext.Utenti.Select(u => new Utente()
                        {
                            id = u.id,
                            user = u.user,
                            password = u.password
                        }).ToList<Utente>();
        }

        if (utenti.Count == 0)
        {
            return NotFound();
        }

        return Ok(utenti);
    }

    [HttpPost]
    public IHttpActionResult PostNewUtente(Utente utente)
    {
        if (!ModelState.IsValid)
            return BadRequest("Not a valid model");

        using (_utenteContext)
        {
            _utenteContext.Utenti.Add(new Utente()
            {
                id = utente.id,
                user = utente.user,
                password = utente.password
            });

            _utenteContext.SaveChanges();
        }

        return Ok();
    }
}
}

EDIT 2 Startup class if it's useful:

using AdrianWebApi.Models;
using AdrianWebApi.Models.DataManager;
using AdrianWebApi.Models.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AdrianWebApi
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<UtenteContext>(options =>{options.UseMySQL("server=localhost;database=dbutenti;User ID=root;password=root;");});
        services.AddScoped<IDataRepository<Utente>, DataManager>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvcWithDefaultRoute();
    }
}
}

EDIT 3 Post method MVC if someone is interested, working, at least for me:

[Route("Add")]
    [System.Web.Http.HttpPost]
    public ActionResult Add([FromForm]Utente utente)
    {
        if (utente.password == null)
        {
            return View();
        }
        else
        {

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:57279/api/");

                //HTTP POST
                var postTask = client.PostAsJsonAsync<Utente>("utente", utente);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return RedirectToAction("GetAll");
                }
            }
            ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
            return View(utente);
        }
    }

Try commenting out your controller and replacing it with this code below, then go to api/utente/ and see if you get a result. If you do then replace what you need with your code.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace AdrianWebApi.Controllers.api
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "Test 1", " Test 2" };
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM