iPhone将xml发布到ASP.net MVC webservices

时间:2011-05-02 12:20:45

标签: iphone xml asp.net-mvc-3 post

是否可以将XMLData从iPhone OS发布到Web服务。 Web服务是使用RESTFul url在ASP.net MVC 3.0中开发的,我们希望iPhone开发人员以XML格式发送输入数据作为POST变量。

webservice actionresult如下所示,其中目击是预期作为POST变量传递的参数

 public ActionResult Update(XDocument sightings)
 {
    try
    {
        XMLHelper xmlHelper = new XMLHelper();
    }
 }

1 个答案:

答案 0 :(得分:2)

这绝对适用您需要做的就是使用NSMutableURLRequest如下:

NSString* sXMLToPost = @"<?xml version=\"1.0\"?><Name>user</Name>";

NSData* data = [sXMLToPost dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:@"http://myurl.com/RequestHandler.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[sXMLToPost dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

if (error) {
//handle the error
}

现在在您的ASHX文件中解析InputStream以阅读发布的XML:

System.IO.Stream str; String strmContents;
Int32 counter, strLen, strRead;

str = Request.InputStream;

strLen = Convert.ToInt32(str.Length);

byte[] strArr = new byte[strLen];

strRead = str.Read(strArr, 0, strLen);

// Convert byte array to a text string.
strmContents = "";
for (counter = 0; counter < strLen; counter++)
{
    strmContents = strmContents + strArr[counter].ToString();            
}

请记住,您始终可以使用以下方式检查请求类型:

  

if(context.Request.RequestType ==“POST”)

MSDN HttpRequest.InputStream