How to send custom headers for remote data requests?

3 posts, 1 answers
  1. Sergi
    Sergi avatar
    34 posts
    Member since:
    Sep 2007

    Posted 21 May 2015 Link to this post


    We have an MVC app with some webapi controllers that use custom security based on a header that the request must include.

    How can we modify the controls to make them include the headers when they request the data to the server?

    As far as we've been seen, we can put the URL they call, but we don't know how to add custom headers.

    Thanks in advance.

  2. Answer
    Rene avatar
    65 posts
    Member since:
    Nov 2010

    Posted 25 May 2015 in reply to Sergi Link to this post

    I am assuming you're referring to ajax calls. 

     We do something like this - you should be able to roll your own based on this:

    <script type="text/javascript">

      $("#RootMenu").css({ "background-color": "transparent", "background": "transparent" });

      $(function () {

        // Setup CSRF safety for AJAX:
        $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
          if (options.type.toUpperCase() === "POST") {
            // We need to add the verificationToken to all POSTs
            var token = $("input[name^=__RequestVerificationToken]").first();
            if (!token.length) return;
            var tokenName = token.attr("name");
            // If the data is JSON, then we need to put the token in the QueryString:
            if (options.contentType.indexOf('application/json') === 0) {
              // Add the token to the URL, because we can't add it to the JSON data:
              options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
            } else if (typeof === 'string' && === -1) {
              // Append to the data string:
     += ( ? "&" : "") + token.serialize();
          var verificationToken = $("meta[name='__AjaxRequestVerificationToken']").attr('content');
          if (verificationToken) {
            jqXHR.setRequestHeader("X-Request-Verification-Token", verificationToken);

     Again - this is just what we do - but you should be able to run with it..



  3. Sergi
    Sergi avatar
    34 posts
    Member since:
    Sep 2007

    Posted 26 May 2015 in reply to Rene Link to this post

    Thanks a lot, that is just what we were looking for.
Back to Top