Reputation: 39
I have a web api in asp.net 4.5. I have installed nuget package for cors and made corresponding code changes
in WebApiConfig.cs
:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
In the controller
[EnableCors(origins: "http://localhost:56241/api/loancopy/3219795539", headers: "*", methods: "*")]
[RoutePrefix("api/loancopy")]
public class MainController : ApiController
{
[HttpPost]
[Route("{loannumber}")]
public HttpResponseMessage PostLoanCopy([FromUri]string loanNumber, [FromBody] LoanDto LoanDto)
{
return new HttpResponseMessage();
}
}
This is my client side post request in angular2
export class HeroService {
private heroesUrl = 'http://localhost:56241/api/loancopy/3219795539';
private body = 'body'
constructor(private http: Http) { }
addHero(name: Loan): Observable<Loan> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.heroesUrl, JSON.stringify(Loan), options)
.map(this.extractData)
.catch(this.handleError);
}
My client says Response for preflight has invalid HTTP status code 500
Upvotes: 0
Views: 1533
Reputation: 563
Looking at your code I presume you followed this documentation
I'm finding it strange that the URL your client calls is exactly the same as the url declared as acceptable origins:
Angular2:
private heroesUrl = 'http://localhost:56241/api/loancopy/3219795539';
WebApiConfig.cs
[EnableCors(origins: "http://localhost:56241/api/loancopy/3219795539", ...
The origins
parameter is used to indicate from which hosts do you accept incomming requests, and the value you seem to be using is the exact same host as the .net
application is running. Consider changing it to the host you are accessing your angular2
aplication.
For example, if you are running it in localhost
, on port 3000
, the EnableCors
declaration should be the following:
[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
Also, as @Developer noted, the origin
declaration should not contain the path, just the host.
So use something like origins: http://localhost:3000
instead of http://localhost:3000/path/to/angular/page
Upvotes: 1