AntiForgery Token作为变量提供,但Controller表示它不存在

时间:2016-04-26 17:54:57

标签: javascript asp.net antiforgerytoken

我正在开发一个ASP.NET网页,并且已经让AntiForgeryTokens适用于大多数POST操作。我无法工作的是上传文件。 我看到令牌正确填充在url中,其他变量,但Controller声称__RequestVerificationToken不存在。

网页代码,最后包含嵌入式JavaScript / Jquery

 @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="vs30px"> &nbsp; </div>
    <div id="division" class="hide_overflow ">

    <div class="vs30px"> &nbsp; </div>
    <div id="division" class="hide_overflow ">
    <table class="Editw_table">
        <tbody>
             <tr>        
                <td colspan="2" >
                    <div>
                    <div style="font-weight:bold;">File Type: </div>
                    <select id="fileSetType">
                        @foreach (var item in Model)
                        {
                            <option value=" @Html.DisplayFor(modelItem => item.filesetTypeId) ">@Html.DisplayFor(modelItem => item.filesetTypeName)</option>
                        }
                    </select>
                    </div>      
                <br />
                </td>
            </tr>
            <tr>
                <td>
                <div  style="font-weight:bold;">File(s):</div>         
                </td>
            </tr>
            <tr>
                 <td >
                   <div class="fileList"></div>
                </td>
            </tr>       
        </tbody>        
    </table>
    <div id="submitTarget"></div>
        <form id="fileUpload" enctype="multipart/form-data">
            <input type="file" id="newFile" style="position:fixed; top: -1000px;"/>
            <div  style="font-weight:bold;"> Comments: </div>         
            <input type="text" id="filesetDetails" size="50" /><br />
        </form>
    </div>  

    <script>
        $(document).ready(function () {
            //uploads a fileset to the server. 
            $('#submitTarget').submit(function (event) {

                event.stopPropagation();

                var verToken = $('[name=__RequestVerificationToken]').val();
                var fileInput = $('#newFile')[0].files;      //the input tag containing the file information.
                var fileSetTypeName = $('#fileSetType :selected').text(); //fetch the file set type stored in the hidden field on the page. 
                var fileSetDetails = document.getElementById("filesetDetails").value;
                var url = "File\\FileUpload?__RequestVerificationToken=" + verToken + "&filesetType=" + fileSetTypeName + "&details=" + fileSetDetails;

                PostBinaryFile(url, fileInput[0]);
            });
        });
    </script>  
    }

JavaScript调用上传文件

function PostBinaryFile(url, file) {
    var buffer = $('.MiddleOuterDiv').spinBuffer();

    var req = new   XMLHttpRequest();
    req.open('POST', url, true);
    req.setRequestHeader("Cache-Control", "no-cache");
    req.setRequestHeader("X-File-Name", file.name);
    req.setRequestHeader("X-File-Size", file.size);
    req.setRequestHeader("Content-type", "multipart/form-data");

    req.addEventListener("load", reqListener);
    req.addEventListener("error", reqListener);
    req.addEventListener("abort", reqListener);

    req.onload = null;
    req.send(file);
}

最后相关的控制器代码功能

 [HttpPost]
 [ValidateAntiForgeryToken]
 [FileErrorHandler]
 public JsonResult FileUpload(string filesetType, string details)
 {
     //Create a new fileset via the API
     FileServices.FileSet fs = new FileServices.FileSet(filesetType, null, details, DateTime.Now, "SYSTEM");
      //Add each file
      string tempFileName = System.IO.Path.GetTempFileName();

      //Get the custom parameters provided
      string fileName = Request["HTTP_X-File-Name"];
      string fileSize = Request["HTTP_X-File-Size"];

      try
      {
          // Read the content of the binary input stream
          byte[] buffer = new byte[Request.InputStream.Length];
          int offset = 0;
          int cnt = 0;
          while ((cnt = Request.InputStream.Read(buffer, offset, 10)) > 0)
          {
              offset += cnt;
          }

          string temporaryFileName = System.IO.Path.GetTempFileName();

          // Write the input stream to a temporary file
          using (FileStream fstream = new FileStream(temporaryFileName, FileMode.Create))
          {
              fstream.Write(buffer, 0, buffer.Length);
              fstream.Flush();
          }

          // Add the zip archive's contents to the filesset.
         int count = fs.AddArchive(temporaryFileName, System.IO.Path.GetFileName(fileName), false);

          fs.SetComplete(true);

          var retVal = new JsonResult
              {
                   Data = new { success = true, error = "none", fileCount = count, message = "Uploaded " + count + " files" },
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
               };

          return retVal;
      }
      catch
      {
          FileServices.FileSet.DeleteFileSet(fs.FileSetId);
          throw;
      }
}

0 个答案:

没有答案