Angular 7 to dotnetcore 2.1 web api call gives no response

爷,独闯天下 提交于 2019-12-07 09:01:27

问题


below is the code from 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;
      });
 }
}

below is the code from angular service,

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

below is the code for 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;
    }


}
} 

}

In fiddler always I can see my post request with length as -1. Not sure what is the problem any help?

Below are from the startup.cs. Is there any flaw in my CORS Settings for dotnetcore2.1 WEB API solution

  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();

    }

回答1:


You should take into consideration that your WEB API service is accesed from a different port than the one from your Angular UI. What hosts your UI in development mode is Angular Cli. This means is that enabling CORS for your WEB API doesn't necessarily enable them for Angular's UI.

By the looks of the image you posted, your Web API's URL would be http://localhost:44389 but the referer is http://localhost:4200.

One way to get around this at a development stage, is by adding to your ClientApp root folder a proxyconfig.json file with a similar configuration to:

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

This way the browser interprets that requests from your Angular UI to your WEB API are from the same origin.

If your WEB API and Angular UI are to be hosted in the same server in production mode I would recommend avoiding CORS. Here's a good article about the subject: https://medium.freecodecamp.org/the-best-ways-to-connect-to-the-server-using-angular-cli-b0c6b699716c

Note: you may need to serve the proxyconfig.json file, here's how: https://www.codeproject.com/Tips/1259121/%2FTips%2F1259121%2FAngular-Proxy-Configuration-for-API-Calls




回答2:


I once had an issue where I had controllers in the same directory as my virtual api route. It looks like this may be the same issue for you. You have:

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

Now, my assumption is (from your namespace) that directory your controller is in is: api/{controllerName}.

Then your api route is: api/[controller]. This means that you now you may have an actual directory and a virtual directory at the same route. When you try to hit your api, dotnet is confused as to whether you are try to access the directory files or the api route. In some circumstances this returns a 401 error others (depending on the browser) will return you nothing.

You can test this theory pretty easily by changing your api route to something like test/[controller] temporarily and then try and hit it.

If this resolves it, then you have 2 options:

  1. Change your api route.
  2. Change your controller directory.



回答3:


The reason is HTTP in base URL. When I updated my base URL to HTTPS it's started working.



来源:https://stackoverflow.com/questions/53804439/angular-7-to-dotnetcore-2-1-web-api-call-gives-no-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!