Reputation: 2654
I've got a .NET Web API
project using Windows Authentication
. In my development environment, I can't do a successful POST
request with data from my Angular
app. It returns:
OPTIONS http://localhost:9090/api/values 401 (Unauthorized)
Failed to load http://localhost:9090/api/values: Response for preflight has invalid HTTP status code 401.
I've tried all means of implementing cors with Microsoft.AspNet.WebApi.Cors
to no avail. But currently I've removed the Microsoft.AspNet.WebApi.Cors
package from my project in favor of the web.config
method (if I actually still need Microsoft.AspNet.WebApi.Cors
installed to do the following in Web.config
, plz let me know):
Web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:5200" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
.NET Web API 'ValuesController.cs':
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace api.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Angular Component (sends data to my Angular service):
constructor(private myService: MyService) {
this.myService.myPost({ID: 1, FirstName: 'Bob'})
.subscribe(
data => console.warn(data),
err => console.error(err),
() => console.log("empty")
);
}
Angular Service (posts the component's data to my Web API
):
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpRequest, HttpHeaders, HttpInterceptor, HttpHandler, HttpEvent, HttpParams} from '@angular/common/http';
import { Observable } from 'rxjs';
import { from } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {
};
public myPost(body) {
const httpOptions = {
withCredentials: true
}
return this.http.post("http://localhost:9090/api/values", body, httpOptions);
}
}
From my research it seems that perhaps I need to pass in an Authorization
header in my request via my httpOptions
variable in the service. But I don't know what to pass as the value for the Authorization
property. See the question marks below:
MyService.ts
public myPost(body) {
const httpOptions = {
headers: new HttpHeaders({
'Authorization': '?????'
}),
withCredentials: true
}
return this.http.post("http://localhost:9090/api/values", body, httpOptions);
}
Maybe this isn't even my problem though. CORS + Windows Authentication - any ideas?
Upvotes: 3
Views: 11936
Reputation: 963
Added :
App_Start/WebApiConfig - Register method:
config.EnableCors();
if does not work, try
FooController:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Upvotes: 0
Reputation: 932
Are you allowing CORS connections from port 4200, which is the default port for Angular applications that use the Angular CLI?
You can also add your headers like this (provided you have a bearer token):
Change the GET below to be a POST.
Using Http
import { Http, Headers, Response } from '@angular/http';
const headers = new Headers({ 'Authorization': 'Bearer ' + token});
const options = {
headers: headers,
withCredentials: true
};
return this.http.get('http://localhost:9090/api/values', options)
.map((response: Response) => {
const stuff = response.json();
return stuff;
}).catch(error => Observable.throw(error));
Using HttpClient
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true
};
this.http
.post('http://localhost:9090/api/values', body, httpOptions)
.pipe(
catchError(this.handleErrors)
).subscribe((result: any) => {
return Observable.of(result);
});
Upvotes: 0