angular - 在使用 Web api 时,预检响应在我的 Angular 项目中具有无效的 http 状态代码 404

标签 angular post asp.net-web-api preflight

我知道这是 CORS 问题。我已经在 web api 服务器端启用了 cors。 Get 方法工作正常,但在处理 post 方法时我遇到了问题。请有人用非常简单的 web api 和客户端示例来回答我。解释如何处理预检、选项等。

控制台

1) zone.js:2935 选项 http://localhost:49975/api/Add_Client_/postgoals 404(未找到)

2) 加载失败 http://localhost:49975/api/Add_Client_/postgoals :预检响应具有无效的 HTTP 状态代码 404。

网络配置

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Content-Type" value="application/json"/>

    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

Angular 帖子方法

    save_Goals(){

  let headers : Headers= new Headers();
  //headers.append('Content-Type','application/x-www-form-urlencoded');
  //headers.append("Access-Control-Allow-Origin","true");
  headers.append('Content-Type', 'application/json');

  headers.append('Access-Control-Allow-Origin','*');
  headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
  headers.append('Access-Control-Allow-Headers','Content-Type');

  let options = new RequestOptions({ headers: headers });

    return this._http.post('http://localhost:49975/api/Add_Client_/postgoals', {goal:'foo'},options)
   .map(res =>  res.json());
  }

谢谢!

最佳答案

我迟到了,但仍然想发布答案,以便对其他人有所帮助。 下面的代码对我来说就像一个魅力!

以下是问题的详细答案:

Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).

我们可以通过不止一种方法将数据传递到 header 中。 语法不同,但含义相同。

// Option 1 
 const httpOptions = {
   headers: new HttpHeaders({
     'Authorization': 'my-auth-token',
     'ID': emp.UserID,
   })
 };


// Option 2

let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');    

let options = {headers:httpHeaders};


// Option 1
   return this.http.post(this.url + 'testMethod', body,httpOptions)

// Option 2
   return this.http.post(this.url + 'testMethod', body,options)

在调用中,您可以找到作为 header 传递的字段,如下图所示: enter image description here

  1. Make changes at the backEnd/Web API side

添加新的 WebApiConfig 文件并添加以下内容。

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "ID", methods: "*") { SupportsCredentials = true }); // In the Header define all the header by comma cepration or you can write * if it works for you.
            /config.EnableCors(enableCorsAttribute);

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

在 Global.asax.cs 文件中添加以下事件

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers","ID");// In the Header define all the header by comma cepration or you can write * if it works for you.
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.End();
            }
        }

在 Web API 端,您可以使用以下语句获取该代码:

 if (Request.Headers.Contains("ID"))
            {
                var ID= Request.Headers.GetValues("ID").First();
            }

对于以下错误,您可以按照以下步骤操作:

  • 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin” header 资源。起源''http://localhost:4200因此不允许 '' 访问

  • 预检响应没有 HTTP 正常状态。

这段代码对我有用,我能够在 HTTP header 中传递 ID,并且我可以在 Web API 端检索相同的 ID。

谢谢,编码愉快!!

关于angular - 在使用 Web api 时,预检响应在我的 Angular 项目中具有无效的 http 状态代码 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48701518/

相关文章:

c# - 如何将 HTML 文件读入 Angular 组件,以便在不重新部署代码的情况下更新 HTML 文件

excel - 从 Excel 中执行 HTTP Post 并解析结果

java - POST登录网站。 java-android

asp.net-web-api - Swagger UI : pass custom Authorization header

jquery - ASP.Net Web Api 是否在单独的 Web 应用程序中?

javascript - 无法在 Angular 5 中将 http 响应作为字符串获取

angular - 绑定(bind)到@Output Observable 而不是回调?

c++ - CInternetSession 安全吗?它被加密了吗?

c# - 使用 yield return 可以返回 JSON "live"吗?

node.js - Angular 2 RC 使用 Express 服务器而不是 Lite 服务器