在我的Angular 6应用程序中,我收到了一个Http 400 Bad Request错误,同时调用了用于登录令牌的API URL。
如果我从POSTMAN调用相同的URL,API工作正常。
但是从Angular应用程序调用时给出错误。
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());
}
任何人都可以帮我解决这个问题。
首先看这篇文章: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...
}
}