How to pass XML as POST to an ActionResult in ASP MVC .NET

后端 未结 7 846
[愿得一人]
[愿得一人] 2020-12-15 10:05

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 wi

7条回答
  •  青春惊慌失措
    2020-12-15 10:39

    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.

提交回复
热议问题