ASP.NET Core为Angular Request返回404

时间:2017-11-22 10:16:50

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

我正在ASP.NET Core使用Angular 2+,现在我有Controller,如下所示:

  public class ValuesController : Controller
  {
    [HttpGet]
    [Route("api/values/get")]
    [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
    public IEnumerable<string> Get()
    {
      return new string[] { "Hello", "DNT" };
    }
  }

我对startup.CS

有这个
public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<DataContext>(options =>
  {
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
  });

  services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.Use(async (context, next) => {
    await next();
    if (context.Response.StatusCode == 404 &&
        !Path.HasExtension(context.Request.Path.Value) &&
        !context.Request.Path.Value.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
    {
      context.Request.Path = "/index.html";
      await next();
    }
  });
  app.UseMvcWithDefaultRoute();
  app.UseDefaultFiles();
  app.UseStaticFiles();

}

AppComponent

    export class AppComponent implements OnInit {
  constructor(private _httpService: Http) { }

  apiValues: string[] = [];

  ngOnInit() {
    this._httpService.get('api/values/get').subscribe(values => {
      this.apiValues = values.json() as string[];
    });
  }
}

当我运行项目时,我得到404 (bad Request)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的路线路径是:&#34; api / values / get&#34;。 因此,请使用此路径进行服务呼叫:

ngOnInit() {
    this._httpService.get('api/values/get').subscribe(values => {
      this.apiValues = values.json() as string[];
    });
  }