ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-05-27 06:51:54  阅读:348  来源: 互联网

标签:c angular angular7 asp-net-core-2-1 asp-net-core-webapi


以下是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;
      });
 }
}

以下是角度服务的代码,

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


}
} 

}

在小提琴手总是我可以看到我的帖子请求长度为-1.不确定有什么问题有什么帮助吗?attached fiddler screenshot for reference

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

  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:44389,但referer是http:// 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,angular7,asp-net-core-2-1,asp-net-core-webapi
来源: https://codeday.me/bug/20190527/1161559.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有