【问题标题】:Response for preflight has invalid HTTP status code 500 says预检响应具有无效的 HTTP 状态代码 500 说
【发布时间】:2017-03-10 20:43:48
【问题描述】:

我在 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

【问题讨论】:

  • 你能不能单独使用origins: "http://localhost:56241/ 作为[Route("{loanNumber}")] 的起点和路线
  • 这意味着您的服务器无法处理该请求。也许您需要对其进行配置以正确响应OPTIONS 请求。

标签: asp.net angular asp.net-web-api http-options-method


【解决方案1】:

看看你的代码,我想你关注了this documentation

我觉得奇怪的是,您的客户端调用的 URL 与声明为可接受来源的 url 完全相同:

Angular2:

private heroesUrl = 'http://localhost:56241/api/loancopy/3219795539';

WebApiConfig.cs

[EnableCors(origins: "http://localhost:56241/api/loancopy/3219795539", ...

origins 参数用于指示您接受来自哪些主机的传入请求,并且您使用的值似乎与正在运行的.net 应用程序的主机完全相同。考虑将其更改为您正在访问angular2aplication 的主机。

例如,如果您在localhost 中运行它,在端口3000 上,EnableCors 声明应如下所示:

[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]

另外,正如@Developer 所指出的,origin 声明不应包含路径,而应仅包含主机。

所以使用类似origins: http://localhost:3000 而不是http://localhost:3000/path/to/angular/page

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-18
    • 2017-09-26
    • 2016-04-14
    • 2018-03-04
    • 2016-02-08
    • 2017-03-15
    • 2017-05-10
    • 2018-04-05
    相关资源
    最近更新 更多