【问题标题】:Can't reach controller from view无法从视图中访问控制器
【发布时间】:2019-06-17 15:19:36
【问题描述】:

我使用 SPA 页面作为视图,并尝试向我的控制器发送请求。我有 200 个代码,但没有来自控制器的数据。我猜是路由有问题,或者我请求的 URL 有误。

就像我认为的那样的 URL

'localhost:5001/api/game', 'localhost:5001/api/game/get'

应该返回 Json 值以查看,但它返回 spa 索引页面。

Controller.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Project.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class GameController : Controller
    {
        [HttpGet("[action]")]
        public async Task<IActionResult> Get()
        {
            return Json(new {test = "123"});
        }
    }
}

程序.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Project
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
    }
}

Startup.cs

namespace project
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<ProjectDbContext>(options => options.UseNpgsql(Configuration.
            GetConnectionString("project_db")));
        services.AddCors();
        services.AddSpaStaticFiles(config => config.RootPath = "Project_front/build");
    }

    // 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();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseCors(builder => {
            builder.AllowAnyHeader();
            builder.AllowAnyMethod();
            builder.AllowAnyOrigin();
        });

        app.UseSpa(spa => {
            spa.Options.SourcePath = "project_front";
            if(env.IsDevelopment()){
                spa.UseReactDevelopmentServer(npmScript:"start");
            }
        });

        app.UseHttpsRedirection();
        app.UseMvc();
    }
 }
}

【问题讨论】:

标签: c# asp.net-core controller


【解决方案1】:

最大的问题是你在调用UseSpa() 之后使用app.UseMvc();

UseSpa() 实际上是一个包罗万象的中间件,正如dos 所描述的那样:

通过返回单页应用程序 (SPA) 的默认页面来处理中间件链中的所有请求。

这个中间件应该放在链的后面,以便其他用于提供静态文件、MVC 操作等的中间件优先。

简而言之,您不应该在UseMvc之前启用此中间件中间件的顺序很重要

另外,在配置 MVC 时最好映射路由:

    ...
    app.UseHttpsRedirection();
        
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
    
    // enable the spa middleware to "catch-all" the requests that are not been processed by previous middlewares
    app.UseSpa(spa => {
        spa.Options.SourcePath = "project_front";
        if(env.IsDevelopment()){
            spa.UseReactDevelopmentServer(npmScript:"start");
        }
    });

【讨论】:

  • 那么我应该在 Startup.cs 中使用路由吗?文档说我可以在控制器的属性中做到这一点,例如 [Route("api/[controller].
  • @EvgenyShmarev RouteAttribute 仅适用于单个控制器。我建议你应该结合这两种方式。
猜你喜欢
  • 1970-01-01
  • 2011-07-07
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 2016-02-02
  • 1970-01-01
相关资源
最近更新 更多