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

后端 未结 7 837
[愿得一人]
[愿得一人] 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:35

    I like the answer from @Freddy and improvement from @Bowerm. It is concise and preserves the format of form-based actions.

    But the IsPostNotification check will not work in production code. It does not check the HTTP verb as the error message seems to imply, and it is stripped out of HTTP context when compilation debug flag is set to false. This is explained here: HttpContext.IsPostNotification is false when Compilation debug is false

    I hope this saves someone a 1/2 day of debugging routes due to this problem. Here is the solution without that check:

    public class XmlApiAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase httpContext = filterContext.HttpContext;
            // Note: for release code IsPostNotification stripped away, so don't check it!
            // https://stackoverflow.com/questions/28877619/httpcontext-ispostnotification-is-false-when-compilation-debug-is-false            
    
            Stream httpBodyStream = httpContext.Request.InputStream;
            if (httpBodyStream.Length > int.MaxValue)
            {
                throw new ArgumentException("HTTP InputStream too large.");
            }
    
            StreamReader reader = new StreamReader(httpBodyStream, Encoding.UTF8);
            string xmlBody = reader.ReadToEnd();
            reader.Close();
    
            filterContext.ActionParameters["xmlDoc"] = xmlBody;
    
            // Sends XML Data To Model so it could be available on the ActionResult
            base.OnActionExecuting(filterContext);
        }
    }
    ...
    public class MyXmlController 
    { ...
        [XmlApiAttribute]
        public JsonResult PostXml(string xmlDoc)
        {
    ...
    

提交回复
热议问题