views:

1054

answers:

4

Hi,

I am trying to provide a simple RESTful API to my ASP MVC project. I will not have control of the clients of this API, they will be passing an XML via a POST method that will contain the information needed to perform some actions on the server side and provide back an XML with the result of the action. I don't have problems sending back XMLs, the problem is receiving XML via a POST. I have seen some JSON examples, but since I will not control my clients (it could be even a telnet from my point of view) I don't think JSON will work. Am I correct?

I have seen examples where clients simply construct the correct form format as part of the body of the request and then the ASP parse the message, and data is available as FormCollection (?param1=value1&param2=value2&,etc). However, I want to pass pure XML as part of the message body.

thanks for your help,

+3  A: 

Why can they not sent the xml as a string in the form post?

Example:

public ActionResult SendMeXml(string xml)
{
  //Parse into a XDocument or something else if you want, and return whatever you want.
}

You could create a form post and send it in a single form field.

Dan Atkinson
In that case the client(s) should be aware on how the server is going to process the request. It will not be XML, it will be a Form with an input text that happens to contain XML. That will not be a RESTful solution.
Freddy
Well, your client needs to be aware of which url they are going to send the request to, so it's not that much of a leap to tell them which form field to use.
Dan Atkinson
There should be no forms, just plain XML. Is not about "which form field to use".
Freddy
Then maybe something like this: http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/Although it looks like you may have something similar already. :)
Dan Atkinson
+3  A: 

This could be accomplished by using the ActionFilterAttribute. Action Filters basically intersects the request before or after the Action Result. So I just built a custom action filter attribute for POST Action Result. Here is what I did:

public class RestAPIAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContextBase httpContext = filterContext.HttpContext;
        if (!httpContext.IsPostNotification)
        {
            throw new InvalidOperationException("Only POST messages allowed on this resource");
        }
        Stream httpBodyStream = httpContext.Request.InputStream;

        if (httpBodyStream.Length > int.MaxValue)
        {
            throw new ArgumentException("HTTP InputStream too large.");
        }

        int streamLength = Convert.ToInt32(httpBodyStream.Length);
        byte[] byteArray = new byte[streamLength];
        const int startAt = 0;

        /*
         * Copies the stream into a byte array
         */
        httpBodyStream.Read(byteArray, startAt, streamLength);

        /*
         * Convert the byte array into a string
         */
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < streamLength; i++)
        {
            sb.Append(Convert.ToChar(byteArray[i]));
        }

        string xmlBody = sb.ToString();

        //Sends XML Data To Model so it could be available on the ActionResult

        base.OnActionExecuting(filterContext);
    }
}

Then on the action result method on your controller you should do something like this:

    [RestAPIAttribute]
    public ActionResult MyActionResult()
    {
        //Gets XML Data From Model and do whatever you want to do with it
    }

Hope this helps somebody else, if you think there are more elegant ways to do it, let me know.

Freddy
A: 

Nice!,

What object I got in my controller method to manipulate the Xml?

I'm using this way:

On actionFilter, I populate the model with:

        .
        .

        string xmlBody = sb.ToString();

        filterContext.Controller.ViewData.Model = xmlBody;

And on my controller method, I get the Model as:

        string xmlUserResult = ViewData.Model as string;

        XmlSerializer ser = new XmlSerializer(typeof(UserDTO));
        StringReader stringReader = new StringReader(xmlUserResult);
        XmlTextReader xmlReader = new XmlTextReader(stringReader);
        UserDTO userToUpdate = ser.Deserialize(xmlReader) as UserDTO;
        xmlReader.Close();
        stringReader.Close();

Is this a correct implementation?

Thanks.

Luís Custódio
A: 

I know you can create a custom value provider factory. This will let you also validate your models when they are posted before attempting to save them. Phil Haack has a blog post about a JSON version of this same concept. The only problem is that I don't know how to implement one this same sort of thing for XML.

Justin