我在 asp.net 4.5 中有一个 web api。我已经为 cors 安装了 nuget 包并进行了相应的代码更改
在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 }
);
}
在控制器中
[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();
}
}
这是我在 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);
}
我的客户说预检响应具有无效的 HTTP 状态代码 500