asp.net mvc - MVC calling external API in View and adding authentication header -


i developing mvc application hosted on web role in azure cloud service. trying send api post request after user push button. have multipart form in view and, instead of calling controller, want post data external api specific in action attribute. code shown below.

@using (html.beginform(null, null, formmethod.post, new { enctype = "multipart/form-data", @action = "http://localhost:55637/api/dataingestion/upload" })) {     <div>         <input type="file" name="fileupload" />         <input type="text" name="filepath" />     </div>      <div>         <button>upload</button>     </div> } 

and external api

because api protected azure active directory, need put authentication token in header of request. token acquired in 1 controller method , stored in tempdata dictionary shown below.

my question how can pass token view , when view try post multipart form data, how can add token header of request?

public actionresult authenticate()     {          uri redirecturi = new uri(redirecturl);          try         {             authenticationcontext ac = new authenticationcontext(authority);             authenticationresult ar = ac.acquiretoken(resourceid, clientid, redirecturi);             string type = ar.accesstokentype;             string token = ar.accesstoken;             tempdata["token"] = token;         }          catch (exception e)         {             //if user cancel login stay @ home page             return redirecttoaction("index");         }          return redirecttoaction("uploadviwe");      } 

any appreciated!

you can send token view using viewbag/modelbinding , bind hiddenfields inside page - let me know if need more here.

once token available on page, need intercept call adding event listener before file upload, can done using jquery file post https://blueimp.github.io/jquery-file-upload/, jquery file upload gives bunch of callback options mentioned here https://github.com/blueimp/jquery-file-upload/wiki/options#callback-options

once you're on listener can add custom headers mentioned in below example.

$('#fileupload').addclass('fileupload-processing');    $.ajax({      url: $('#fileupload').fileupload('option', 'url'),      datatype: 'json',    type: 'get',    beforesend: function(xhr) {      xhr.setrequestheader('authorization', "[token here]");    }

or example

$('#upload_btn').fileupload({      singlefileuploads: true,      beforesend: function(xhr, data) {          var file = data.files[0];          xhr.setrequestheader('[header name]', '[header value]');      },  });


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -