MVC控制器找不到Api控制器(同一项目)

时间:2019-03-20 15:15:20

标签: c# api asp.net-core asp.net-core-mvc

(对不起,如果我的英语有点烂)

我正在尝试从MVC控制器调用api方法,但mvc似乎无法找到该方法。我在mvc控制器中将路由设置为

[Route("[controller]")]

,并且在api控制器中为

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

在startup.cs文件中,我添加了此命令以启用默认路由

app.UseMvcWithDefaultRoute();

Mvc控制器代码:

[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代码:

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

问题可能是我在同一个项目中同时使用了mvc和api控制器的旧示例,但是我想请大家帮忙。

在:

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

无论我对代码进行了什么更改,我总是得到{StatusCode:404,ReasonPhrase:'Not Found',...}。

编辑:

整个Api控制器(我也在尝试使用POST方法,但是它也不起作用)

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

编辑2 启动类(如果有用):

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

编辑3 :如果有人感兴趣,至少对我来说,发布方法MVC:

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

1 个答案:

答案 0 :(得分:0)

尝试注释掉您的控制器,并用下面的代码替换它,然后转到api/utente/,看看是否有结果。如果这样做,则用代码替换所需的内容。

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