【问题标题】:Get a custom header in angular $http from web api controller从 web api 控制器获取 angular $http 中的自定义标头
【发布时间】:2016-05-25 16:11:23
【问题描述】:

我正在尝试在我的 HttpResponseMessage 中传递一条信息以及我的内容,例如:

        string jsonFiles = JsonConvert.SerializeObject(listFiles);
        HttpResponseMessage response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StringContent(jsonFiles)
        };
        response.Headers.Add("Key", "Value");

        return response;

但是,在我的角度调用和响应中,我在 response.config.headers 或 response.headers 中看不到“Key”标头。知道为什么吗?

  $http.get("/api/Locker").then(function (response) {
        console.log(response);
        console.log(response.headers);
        console.log(response.config.headers);
  });

在我的 Startup.cs 中我确实有:

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config); 

【问题讨论】:

  • 您可以尝试使用带有 4 个参数(响应、状态、标头、配置)的成功重载并访问标头吗?
  • 未定义。但是,如果我只使用响应,则响应对象具有所有这些属性。 Response.config.headers 有一个 Accepted 头和一个 Bearer 头,但不是我添加的。
  • 根据文档 response.config 返回发送请求时使用的配置。 response.headers 是一个函数。尝试使用 response.headers("Key") 看看是否有帮助。
  • 工作就像一个魅力萨拉西如果你想回答我会接受的
  • 添加为答案。很高兴它成功了。

标签: angularjs http asp.net-web-api response


【解决方案1】:

根据文档response.config 返回发送请求时使用的配置。 response.headers 是一个函数。尝试使用response.headers("Key") 看看是否有帮助。

【讨论】:

    【解决方案2】:

    您必须将自定义标头显式添加到您的 CORS 策略中,否则 AngularJS 将无法读取它。改变这个:

    app.UseCors(CorsOptions.AllowAll);
    

    到这里:

    var policy = new CorsPolicy
    {
        AllowAnyHeader = true,
        AllowAnyMethod = true,
        AllowAnyOrigin = true,
        SupportsCredentials = true
    };
    
    policy.ExposedHeaders.Add("MyHeader");
    
    app.UseCors(new CorsOptions
    {
        PolicyProvider= new CorsPolicyProvider
        {
            PolicyResolver = c => Task.FromResult(policy)
        }
    });
    

    【讨论】:

    • 然后您必须使用Fiddler 检查您的HTTP 响应,并检查您的自定义标头和Access-Control-Allow-Origin 标头是否存在且正确。此外,请始终确保您对app.UseCors 的调用管道中的任何其他 OWIN 中间件之前进行。
    • 我一直在这样做。 Sarathy 在 cmets 中的回答对我有用。无需使用 CORS 进行任何更改。
    【解决方案3】:

    我正在使用 WebApi 版本 5.2.3。要导出响应标头,您可以尝试创建自定义属性,例如

    public class CustomHeadersAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            actionExecutedContext.Response.Headers.Add("Access-Control-Expose-Headers", "<Your Custom Key>");
            base.OnActionExecuted(actionExecutedContext);
        }
    }
    

    然后在您的控制器或任何您需要的地方,添加

    [CustomHeaders]
    public HttpResponseMessage GetMethod() { ... }
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2018-08-11
      • 2018-09-26
      • 2015-10-18
      • 2018-02-07
      • 2019-06-12
      • 2017-12-10
      • 1970-01-01
      • 2016-05-03
      相关资源
      最近更新 更多