1

In my Angular 6 application I am getting a Http 400 Bad Request error ,while calling the API url for login token .

The API is working fine if I call the same url from POSTMAN.

But giving an error when called from the Angular application.

Service.ts (Angular)

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

Can anyone help me to fix this .

Zhu
  • 2,671
  • 9
  • 27
  • 64

1 Answers1

0

first see this post : Access-control-allow-origin with multiple domains

then if you need see this page : Enable cross-origin requests in ASP.NET Web API 2

quick guide for Enable cross-origin requests in ASP.NET Web API 2 in three steps:

do the following: 1. first install

Install-Package Microsoft.AspNet.WebApi.Cors

2.Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

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. Next, add the [EnableCors] attribute to the TestController class:

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...
    }
}
Masoud Bimar
  • 5,860
  • 4
  • 22
  • 29