[英]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.