This is a migrated thread and some comments may be shown as answers.
How to send custom headers for remote data requests?
2 Answers 25 Views
This is a migrated thread and some comments may be shown as answers.
Sergi
Top achievements
Rank 1
Sergi asked on 21 May 2015, 02:01 PM

Hello.

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 Answers, 1 is accepted

Sort by
0
Accepted
Rene
Top achievements
Rank 1
answered on 26 May 2015, 04:00 AM

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 options.data === 'string' && options.data.indexOf(tokenName) === -1) {
          // Append to the data string:
          options.data += (options.data ? "&" : "") + 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..

 

Rene.

0
Sergi
Top achievements
Rank 1
answered on 26 May 2015, 07:07 AM
Thanks a lot, that is just what we were looking for.
Asked by
Sergi
Top achievements
Rank 1
Answers by
Rene
Top achievements
Rank 1
Sergi
Top achievements
Rank 1
Share this question
or