【发布时间】:2016-08-24 17:09:36
【问题描述】:
我在这里遇到了一个小问题。
目前我正在使用通用处理程序将文件上传到服务器,但我遇到的一个问题是,如果我有额外的数据,例如用户名和姓氏,我必须单独执行(保存)。
这是一个问题,因为如果我保存姓名和姓氏,并且文件上传失败,我的数据库中有一条记录没有与之关联的文件。
所以,现在我正在考虑实现一个新的 Web 方法,它将承担所有这些,如果该方法失败,它只会回滚 SQL 事务。
我要做的是调用一个web方法,并传递带有用户名和姓氏和照片的文件,然后在那里执行保存到数据库中。
这是我尝试过的:
jQuery:
$("#btnCreateRequest").click(function () {
var data = new FormData();
var photo = $("#fuPhoto")[0].files[0];
data.append("name", 'Fred');
data.append("surname", 'Moller');
data.append("photo", photo);
$.ajax({
type: "POST",
url: "Service.svc/CreateRequest",
dataType: "json",
//cache: false,
contentType: false,
processData: false,
data: data,
success: function (response2) {
//$("#PageArea").html(response2);
Popup(true, "success", "success", true);
},
error: function (response) {
Popup(true, "Error", JSON.stringify(response), true);
}
});
});
IService.cs
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "CreateRequest",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CreateRequest();
服务.svc
public string CreateRequest()
{
var request = System.Web.HttpContext.Current.Request;
string name = request["name"];
string surname = request["surname"];
HttpPostedFile photo = request["photo"];
//Saving in database happens here, using above variables...
return "whatever";
}
但是,我失败得很惨。
Web 服务被调用,但所有变量均为 NULL。
如果我以错误的方式解决此问题,请指出正确的方向 - 任何帮助将不胜感激!
(如果有不清楚的地方,请询问,我会尽力解释更多)
【问题讨论】:
-
尝试将
BodyStyle设置为Bare。 -
刚刚试过 - 它仍然没有得到变量值:(
标签: c# jquery web-services wcf-rest