在Angular 6应用程序中,我在调用登录令牌的API URL时遇到Http 400错误请求错误。
如果我从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());
}
谁能帮我解决这个问题。
答案 0 :(得分:0)
首先看到这篇文章: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...
}
}