我正在开发一个Ionic 3移动应用程序,我对Angular的POST方法有疑问。
在登录页面中,我创建了一个表单并尝试使用Angular HTTP POST方法将数据发送到服务器。但在服务器(.NET WEB API)中,我看到请求的标头为空。
这是Angular边码;
login(username, password):Observable<Object>{
let url : string = this.apiUrl+"/login";
let headers = new HttpHeaders();
headers.append('Authorization', btoa(username+":"+password).toString());
return this.http.post(url,JSON.stringify({username,password}), {headers: headers});
}
以下是控制器的.NET端代码;
[EnableCors(origins: "http://localhost:8100", headers: "*", methods: "*")]
public Response Post()
{
return _mobileUserService.Login();
}
以下是catch请求的.NET端代码部分;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var token = request.Headers.GetValues("Authorization").FirstOrDefault();
}
catch (Exception ex)
{
}
return base.SendAsync(request, cancellationToken);
}
当.NET(在运行中)捕获请求时,我会看到&#34; request&#34;的这些值。变量;
request = {Method: POST, RequestUri: 'http://localhost:41582/api/login', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:
{
Connection: keep-alive
Accept: application/json
Accept: text/plain
Accept: */*
...
通常,请求的网址是localhost:8100,所以我认为服务器接受了CORS
我该如何解决?
答案 0 :(得分:1)
在Web api中,你必须根据你的路线设置来判断发布或获取哪种方法。
[EnableCors(origins: "http://localhost:8100", headers: "*", methods: "*")]
[HttpPost] // Decorate post this attribute in your controller
public Response Post()
{
return _mobileUserService.Login();
}