ASP.NET Web Service使用会话传递表单数据

时间:2014-09-21 09:01:05

标签: c# web-services session webforms

我试图通过ASP.NET Webform中的AJAX上传图像。它很顺利,接受当我传递表单数据时,我似乎无法访问我的会话值。

这就是我的尝试。

ASPX(摘录)

<asp:FileUpload runat="server" ID="profileImageFU" CssClass="profile-image-fu"/>
<input type="button" id="profileImageSaveBtn" class="profile-image-save-btn" />
<progress></progress>

JS

$(document).ready(function () {
        var file, name, size, type;
        $('.profile-image-fu').change(function () {
            file = this.files[0];
            name = file.name;
            size = file.size;
            type = file.type;
        });
        $('.profile-image-save-btn').click(function (e) {
            e.preventDefault();
            var fileInput = $('.profile-image-fu')[0];
            var fileData = $(fileInput).prop("files")[0];   // Getting the properties of file from file field
            var formData = new window.FormData();                  // Creating object of FormData class
            formData.append("file", fileData); // Appending parameter named file with properties of file_field to form_data

            $.ajax({
                url: 'ImageUploaderHandler.ashx',
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (data) {
                    alert('success!');
                },
                error: function (errorData) {
                    alert('error!');
                }
            });
        });
    });

ImageUploaderHandler.ashx(摘录)

public void ProcessRequest (HttpContext context) {
    string result = (new UserWS()).setProfileImage(context);
}

UserWS(摘录)

[WebMethod(EnableSession = true)]
public string setProfileImage(object context)
{
    ....
    // Get the uploaded image from the Files collection (WORKS GREAT, I put a break point here and I see postedFile contains all the details I need)
    HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];
    if (HttpContext.Current.Session["User"] != null) {
        // PROBLEM: I need to do my code here, but my Session["User"] is null, even though it's not.
        // EDIT: My HttpContext.Current.Session = null

    }
}

我在其他Web服务中使用过[WebMethod(EnableSession = true)],它运行正常。我猜这个错误是因为我在这里传递来自AJAX的表单数据。

1 个答案:

答案 0 :(得分:0)

这可能是一种落后的方法,但服务中可能需要cookie?只是来自this article的想法(接近结尾)。