【发布时间】:2014-11-15 10:40:25
【问题描述】:
我正在尝试通过 ASP.NET Webform 中的 AJAX 上传图像。一切顺利,接受当我传递表单数据时,我似乎无法访问我的会话值。
这是我尝试过的。
ASPX (sn-p)
<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 (sn-p)
public void ProcessRequest (HttpContext context) {
string result = (new UserWS()).setProfileImage(context);
}
用户WS (sn-p)
[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 传递表单数据造成的。
【问题讨论】:
-
您能否通过将
withCredtials设置为true 来检查使用xhrFields 是否有效? -
我尝试添加 xhrFields: { withCredentials: true } 但仍然是同样的问题。会话为空。
标签: c# web-services session webforms