c# - Angular 7 到 dotnetcore 2.1 web api 调用没有响应

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

下面是来自 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 操作的代码,

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


}
} 

在 fiddler 中,我总是可以看到长度为 -1 的 post 请求。不确定有什么问题有帮助吗? attached fiddler screenshot for reference

以下来自 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();

    }

最佳答案

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

从您发布的图片来看,您的 Web API 的 URL 应该是 http://localhost:44389refererhttp://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

关于c# - Angular 7 到 dotnetcore 2.1 web api 调用没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804439/

相关文章:

angular - 自定义错误处理程序抛出错误 : Cannot read property 'get' of undefined ( Injector )

angular - highlight.js 不适用于 Angular 2

arrays - 复杂对象的 json 数组在发布时始终为 null

c# - 无法将路由映射到操作,ASP.NET Core Web API

docker - 添加迁移 : Cannot bind argument to parameter 'Path' because it is an empty string

c# - 尝试访问 ASP.NET Web App 项目上的本地主机时出现 ERR_CONNECTION_RESET

c# - 防止 TFS 添加临时文件

angular - 在 Typescript/Angular2 中显示 bootbox 警报?

c# - 从 C# 调用非托管 C DLL 函数(带有指向结构的指针和指向 bool 数组的指针)

c# - 切换列表中不同的和实际的项目