【问题标题】:MVC calling external API in View and adding authentication headerMVC 在 View 中调用外部 API 并添加身份验证标头
【发布时间】:2015-10-14 12:28:28
【问题描述】:

我正在开发一个托管在 Azure 云服务中的 Web 角色上的 MVC 应用程序。我要做的是在用户按下按钮后发送 API 发布请求。我的视图中有这个多部分表单,而不是调用控制器,我只想将此数据发布到 action 属性中特定的外部 API。代码如下所示。

@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>
}

而外部API是这样的

由于该 API 受 Azure Active Directory 保护,我需要将身份验证令牌放在请求的标头中。令牌在一种控制器方法中获取并存储在 TempData 字典中,如下所示。

我的问题是如何将此令牌传递给视图,当视图尝试发布多部分表单数据时,如何将令牌添加到请求的标头?

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 the login then stay at home page
            return RedirectToAction("Index");
        }

        return RedirectToAction("UploadViwe");

    }

任何帮助将不胜感激!

【问题讨论】:

    标签: asp.net-mvc azure asp.net-web-api


    【解决方案1】:

    您可以使用 ViewBag/ModelBinding 将令牌发送到视图并将其绑定到页面内的 HiddenFields - 如果您需要更多帮助,请告诉我。

    一旦令牌在页面上可用,您需要在文件上传之前通过添加事件侦听器来拦截调用,这可以使用 jquery 文件发布https://blueimp.github.io/jQuery-File-Upload/ 来完成,jquery 文件上传提供了一堆回调选项为这里提到https://github.com/blueimp/jQuery-File-Upload/wiki/Options#callback-options

    一旦您在监听器上,您可以添加自定义标题,如下例中所述。

    $('#fileupload').addClass('fileupload-processing');
      $.ajax({
        url: $('#fileupload').fileupload('option', 'url'),
        dataType: 'json',
      type: 'GET',
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', "[token here]");
      }

    还是这个例子

    $('#upload_btn').fileupload({
        singleFileUploads: true,
        beforeSend: function(xhr, data) {
            var file = data.files[0];
            xhr.setRequestHeader('[Header name]', '[Header Value]');
        },
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多