Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to pass XML as POST to an ActionResult in ASP MVC .NET

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@Freddy - liked your approach and improved on it with the following code to simplify stream reading:

    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.");
        }

        StreamReader reader = new StreamReader(httpBodyStream, Encoding.UTF8);
        string xmlBody = reader.ReadToEnd();
        reader.Close();

        filterContext.ActionParameters["message"] = xmlBody;

        // Sends XML Data To Model so it could be available on the ActionResult
        base.OnActionExecuting(filterContext);
    }

Then in the Controller you can access the xml as a string:

[RestAPIAttribute]    
public ActionResult MyActionResult(string message)    
{         

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...