【问题标题】:Angular 7 to dotnetcore 2.1 web api call gives no responseAngular 7 到 dotnetcore 2.1 web api 调用没有响应
【发布时间】:2019-05-17 04:24:07
【问题描述】:

下面是 login.component.ts 的代码,

login() {
const val = this.form.value;

if (val.email && val.password) {
  this.authService.login(val.email, val.password)
    .subscribe(
      data => {

        if (data && data.Token) {
          // store user details and jwt token in local storage to keep user logged in 
          //between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(data));
          console.log("user logged in");
          this.router.navigate([this.returnUrl]);
        } else {
          console.log("user not logged in");
        }

      },
      error => {
        this.error = error;
      });
 }
}

下面是 Angular 服务的代码,

login(email: string, password: string) {
 return this.http.post<User>(this.baseUrl + "Authenticate", { email, 
password }, httpOptions);
}

下面是dotnetcore 2.1 web api action的代码,

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using API.Utilities;
using Business.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;


namespace API.Controllers
{
  [Authorize]
  [Produces("application/json")]
  [Route("api/[controller]")]
  public class UsersController : BaseController
{
    private readonly AppSettings _appSettings;

    public UsersController(IOptions<AppSettings> appSettings)
    {          
        _appSettings = appSettings.Value;
    }

    [AllowAnonymous]
    [HttpPost]
    [Route("Authenticate")]
    public IActionResult Authenticate([FromBody]User userParam)
    {
        var user = Authenticate(userParam.Email, userParam.Password);

        if (user == null)
            return BadRequest(new { message = "Username or password is incorrect" });

        return Ok(user);
    }



    public User Authenticate(string username, string password)
    {
        //////code goes

        return user;
    }


}
} 

}

在提琴手中,我总是可以看到长度为 -1 的帖子请求。不知道是什么问题有什么帮助?

以下来自于 startup.cs。我的 dotnetcore2.1 WEB API 解决方案的 CORS 设置是否有任何缺陷

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).
            AddJsonOptions(options => {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        });

        services.AddDistributedMemoryCache();

        services.AddSession(options => {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(36000);
            options.Cookie.HttpOnly = true;
        });

        services.AddCors(options => {
            options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
        });
    }

    // 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
        {
            app.UseHsts();
        }

        app.UseStaticFiles();

        app.UseCors(x => x
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
        app.UseSession();
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseMvc();

    }

【问题讨论】:

  • 你的控制器/动作方法是否受到 Angular 的影响?
  • 从 Angular 调用时,我无法命中 WEB API 控制器动作断点。
  • 对于这个请求,它似乎正在处理CORS,您是否在Starup.cs 中启用了cors,例如` app.UseCors(opt => { opt.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin( ) .AllowCredentials(); }); `
  • 是的,我已启用 CORS。但似乎未应用,因为有时在控制台中我可以看到 cors 被阻止,但该错误仅在一段时间后出现
  • app.UseHttpsRedirection(); 可能会导致问题。尝试删除它

标签: c# angular asp.net-core-webapi angular7 asp.net-core-2.1


【解决方案1】:

您应该考虑到您的 WEB API 服务是从不同的端口访问的,而不是从您的 Angular UI 访问的端口。在开发模式下托管您的 UI 的是 Angular Cli。这意味着为您的 WEB API 启用 CORS 并不一定为 Angular 的 UI 启用它们。

根据您发布的图片的外观,您的 Web API 的 URL 将是 http://localhost:44389,但 refererhttp://localhost:4200

在开发阶段解决此问题的一种方法是在您的 ClientApp 根文件夹中添加一个具有类似配置的 proxyconfig.json 文件:

{
  "/api/*": {
  "target": "https://localhost:44389",
  "secure": true,
  "changeOrigin": true
  }
}

这样,浏览器就会解释从 Angular UI 到 WEB API 的请求来自同一来源。

如果您的 WEB API 和 Angular UI 要在生产模式下托管在同一台服务器上,我建议避免使用 CORS。这是一篇关于这个主题的好文章:https://medium.freecodecamp.org/the-best-ways-to-connect-to-the-server-using-angular-cli-b0c6b699716c

注意:您可能需要提供 proxyconfig.json 文件,方法如下:https://www.codeproject.com/Tips/1259121/%2FTips%2F1259121%2FAngular-Proxy-Configuration-for-API-Calls

【讨论】:

  • 当我使用 https 直接更新 service.ts 中的基本 url 时,它开始工作了。
  • 很高兴知道这一点。但请注意,如果 Web API 和 Angular UI 都将在生产环境中由同一台服务器托管,那么 CORS 不是最佳选择。
  • 感谢您的建议。如果您有其他选择,请告诉我。
  • 当然,请阅读我在回答中分享的文章的生产方法部分。
【解决方案2】:

原因是基本 URL 中的 HTTP。当我将基本 URL 更新为 HTTPS 后,它就开始工作了。

【讨论】:

    【解决方案3】:

    我曾经遇到过一个问题,即我的控制器与我的虚拟 api 路由位于同一目录中。看起来这可能对你来说是同样的问题。你有:

    namespace API.Controllers
    {
      [Authorize]
      [Produces("application/json")]
      [Route("api/[controller]")]
      public class UsersController : BaseController
    {
    

    现在,我的假设是(根据您的命名空间)您的控制器所在的目录是:api/{controllerName}

    那么你的 api 路由是:api/[controller]。这意味着您现在可能在同一路径上有一个实际目录和一个虚拟目录。当您尝试访问您的 api 时,dotnet 会混淆您是尝试访问目录文件还是 api 路由。在某些情况下,这会返回 401 错误,而其他(取决于浏览器)将不会返回任何内容。

    您可以通过将您的 api 路由临时更改为 test/[controller] 之类的方式来非常轻松地测试这个理论,然后尝试点击它。

    如果这解决了它,那么你有两个选择:

    1. 更改您的 api 路由。
    2. 更改您的控制器目录。

    【讨论】:

    • 已更改为 test/[controller] 但仍无法正常工作。似乎我的问题不同
    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多