System.AccessViolationException' 发生在 Azure.dll 上的 System.Net

本文关键字:System Azure dll 上的 Net AccessViolationException | 更新日期: 2023-09-27 18:34:38

我正在为这个问题拔头发,我想知道是否有人可以提供帮助。

我正在尝试创建一个 POST 和 PUT http web api 方法来处理 JSON 数据和图像数据。当使用 Azure 模拟器在我的本地计算机上运行时,这一切都可以完美运行,但是一旦我发布到服务器,我就会收到一个 AccessViolationException 错误,指出:

其它信息:尝试读取或写入受保护的内存。这通常表示其他内存已损坏。

我使用以下代码,在针对 Azure 进行调试时,读取多部分数据时代码失败。

public async Task<bool> BindModelTask(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext) {
        try {
            if (actionContext.Request.Content.IsMimeMultipartContent()) {
                var provider = await actionContext.Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
                FormCollection formData = provider.FormData;
                FileData[] fileData = provider.GetFiles().Result;
                if (formData != null && formData.Count == 1) {
                    Pet pet = (Pet)Newtonsoft.Json.JsonConvert.DeserializeObject(formData[0], typeof(Pet));
                    if (pet != null) {
                        petModel petModel = new petModel(pet);
                        if (fileData != null) {
                            petModel.file = fileData.FirstOrDefault();
                        }
                        bindingContext.Model = petModel;
                    }
                }
                return true;
            }
        }
        catch (Exception ex) { throw ex; }
    }
}

public class InMemoryMultipartFormDataStreamProvider : MultipartStreamProvider {
    private FormCollection _formData = new FormCollection();
    private List<HttpContent> _fileContents = new List<HttpContent>();
    // Set of indexes of which HttpContents we designate as form data
    private Collection<bool> _isFormData = new Collection<bool>();
    /// <summary>
    /// Gets a <see cref="NameValueCollection"/> of form data passed as part of the multipart form data.
    /// </summary>
    public FormCollection FormData {
        get { return _formData; }
    }
    /// <summary>
    /// Gets list of <see cref="HttpContent"/>s which contain uploaded files as in-memory representation.
    /// </summary>
    public List<HttpContent> Files {
        get { return _fileContents; }
    }
    /// <summary>
    /// Convert list of HttpContent items to FileData class task
    /// </summary>
    /// <returns></returns>
    public async Task<FileData[]> GetFiles() {
        return await Task.WhenAll(Files.Select(f => FileData.ReadFile(f)));
    }
    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) {
        // For form data, Content-Disposition header is a requirement
        ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
        if (contentDisposition != null) {
            // We will post process this as form data
            _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
            return new MemoryStream();
        }
        // If no Content-Disposition header was present.
        throw new InvalidOperationException(string.Format("Did not find required '{0}' header field in MIME multipart body part..", "Content-Disposition"));
    }
    /// <summary>
    /// Read the non-file contents as form data.
    /// </summary>
    /// <returns></returns>
    public override async Task ExecutePostProcessingAsync() {
        // Find instances of non-file HttpContents and read them asynchronously
        // to get the string content and then add that as form data
        CloudBlobContainer _container = StorageHelper.GetStorageContainer(StorageHelper.StorageContainer.Temp);
        for (int index = 0; index < Contents.Count; index++) {
            if (_isFormData[index]) {
                HttpContent formContent = Contents[index];
                // Extract name from Content-Disposition header. We know from earlier that the header is present.
                ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
                string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;
                // Read the contents as string data and add to form data
                string formFieldValue = await formContent.ReadAsStringAsync();
                FormData.Add(formFieldName, formFieldValue);
            }
            else {
                _fileContents.Add(Contents[index]);
            }
        }
    }
    /// <summary>
    /// Remove bounding quotes on a token if present
    /// </summary>
    /// <param name="token">Token to unquote.</param>
    /// <returns>Unquoted token.</returns>
    private static string UnquoteToken(string token) {
        if (String.IsNullOrWhiteSpace(token)) {
            return token;
        }
        if (token.StartsWith("'"", StringComparison.Ordinal) && token.EndsWith("'"", StringComparison.Ordinal) && token.Length > 1) {
            return token.Substring(1, token.Length - 2);
        }
        return token;
    }
}

正如我所说,此代码在本地计算机上运行时可以完美运行,但在 Azure 上运行时则不然。

有什么想法吗?

谢谢

尼尔

System.AccessViolationException' 发生在 Azure.dll 上的 System.Net

我知道

这是一个较旧的帖子,但我有同样的例外,我希望对我有用的东西可以帮助其他人。就我而言,问题在于System.Net.Http的版本不匹配。这些是我为修复而采取的步骤。

  1. 删除对 System.Net.Http 的所有引用
  2. 从Nuget获取System.Net.Http
  3. 确保绑定在我的应用程序/web.config 中({版本} = dll 版本(
<dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-{version}" newVersion="{version}" />
</dependentAssembly>

希望这有帮助!