[英]How to implement the C# server side when using ASIFormDataRequest?
我正在尝试使用 ASIFormDataRequest 将数据发送到 ASP.net 服务器端。 我已经创建了一个 aspx 页面。目前我可以得到这两个纯文本。 但是我不知道如何通过 Request.Form 在 C# 中传递 NSdata。
这是 Obj-C 代码:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"name"];
[request setPostValue:@"Copsey" forKey:@"code"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];
这是当前 C# 代码:
string name = Request.Form["name"] == null ? "" : Request.Form["name"];
string code = Request.Form["code"]==null?"":Request.Form["code"];
如您所见,在 iphone 中,我尝试将图像发送到 C# 服务器端,但我不知道该怎么做?
要将图像发送到 WCF REST 服务,使用 ASIFormDataRequest .. 这是我们在生产中的项目的示例...
假设我在一个名为“image”的变量中有一个 UIImage
NSString *surl = @"http:www.SomeRestService.com"
NSURL *url = [NSURL URLWithString:surl];
ASIFormDataRequest *r = [ASIFormDataRequest requestWithURL:url];
[r setValidatesSecureCertificate:NO];
[r setTimeOutSeconds:30];
[r setRequestMethod:@"POST"]; //default is POST (insert),
[r setDelegate:self];
[r setDidFailSelector:@selector(requestDidFail:)];
//[r addRequestHeader:@"Content-Type" value:@"application/json"] this will cause the call to fail. No content-type header for this call.
NSMutableData *imageData = [NSMutableData dataWithData:UIImageJPEGRepresentation(image, .35)]; //we are really compressing our images.. you can do what you want, of course.
[r setPostBody:imageData];
[r setDidFinishSelector:@selector(imageSaveDidFinish:)];
[r startAsynchronous];
OK, on the WCF side, you need to define a method that receives a System.IO.Stream, and that Stream needs to be the last parameter defined, it sould be a POST, and should not contain any other parameters as part of the POST 正文(您可以在 URL 和查询字符串中定义参数,尽管一些纯粹主义者会说这对于 REST POST 来说是不好的形式)。
[WebInvoke(UriTemplate = "Upload", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
public GenericObject SaveReceiptImage(System.IO.Stream imageStream)
{
try
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read = 0;
while ((read = imageStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
ms.Position = 0;
if (ms.Length > 0)
{
//save your byte array to where you want
}
else
{
// woops, no image was passed in
}
}
}
catch (Exception ex)
{
//bad error occured, log it
}
return whatever;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.