【问题标题】:Angular 6 : 400 bad request when calling API url for getting Auth tokenAngular 6:调用 API url 获取 Auth 令牌时出现 400 错误请求
【发布时间】:2019-04-06 04:06:05
【问题描述】:

在我的 Angular 6 应用程序中,我在调用登录令牌的 API url 时收到 Http 400 Bad Request 错误。

如果我从 POSTMAN 调用相同的 url,API 工作正常。

但是从 Angular 应用程序调用时会出错。

Service.ts(角度)

Get_User_Token(Email, Password) {
    var data = "username=" + Email + "&password=" + Password + "&grant_type=password";
    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded', 'No-Auth': 'True' });
    return this.http.post(this.BASE_URL + '/token', data, { headers: reqHeader });
  }

web.config

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
      </customHeaders>
    </httpProtocol>

startup.cs

   public void Configuration(IAppBuilder app)
        {

            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                AllowInsecureHttp = true
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

谁能帮我解决这个问题。

【问题讨论】:

  • 能否请您向我们展示 webapi 控制器并启动
  • 请查看更新后的帖子@MasoudBimar

标签: angular typescript asp.net-web-api bearer-token bad-request


【解决方案1】:

首先看到这个帖子:Access-control-allow-origin with multiple domains

如果您需要查看此页面:Enable cross-origin requests in ASP.NET Web API 2

分三步在 ASP.NET Web API 2 中启用跨域请求的快速指南:

执行以下操作: 1. 先安装

Install-Package Microsoft.AspNet.WebApi.Cors

2.打开文件 App_Start/WebApiConfig.cs。将以下代码添加到 WebApiConfig.Register 方法中:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

3。接下来,将[EnableCors] 属性添加到TestController 类:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2021-03-22
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2022-08-22
    相关资源
    最近更新 更多