【问题标题】:How can I send custom header of cross origin request in AngularJS + Web Api 2?如何在 AngularJS + Web Api 2 中发送跨源请求的自定义标头?
【发布时间】:2019-05-31 15:02:20
【问题描述】:

我有一个 Web Api 2 项目:

[AuthorizeUser]
public class ValuesController : ApiController
{
    [Route("api/value/get")]
    [HttpPost]
    public IHttpActionResult Get()
    {
        return Ok("Hello world!");
    }
}

以及WebApiConfig.cs中的配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

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

以及来自客户端 AngularJS 的请求:

$scope.getvalue = function () {
            var url = "http://localhost:59073/api/value/get";
            $http({
                method: "POST",
                url: url,
                header: {
                    'x-access-token': 'abc'
                }
            }).then(function onSuccess(res) {
                console.log(res);
            }).then(function onError(err) {
                console.log(res);
            });
        }

但我无法在服务器端获取 POST 请求标头的自定义标头“x-access-token”。而且我在 Chrome 的网络选项卡中也没有看到任何 OPTIONS 请求。

【问题讨论】:

    标签: c# angularjs cors asp.net-web-api2


    【解决方案1】:

    我知道这为时已晚。它将帮助遇到同样问题的人。在您的示例中,您为 header 属性分配了一个对象。我认为这是一个错字。它应该是标题而不是标题。

    var req = {
       method: 'POST',
       url: 'http://example.com',
       headers: {
          'Content-Type':'x-access-token': 'abc'
       },
       data: { test: 'test' }
    }
    
    $http(req).then(function(){...}, function(){...});
    

    请参考Angular1.x的官方文档

    https://docs.angularjs.org/api/ng/service/$http#setting-http-headers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2018-04-25
      • 2012-12-09
      • 2017-05-02
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      相关资源
      最近更新 更多