How do I access the request body in XML format in

2019-09-07 13:02发布

问题:

I can create a WCF REST service and POST, PUT and GET data OK.

How do I access the request body in XML format on the service side to send to an SQL database?

回答1:

You can actually pass arguments to to your web methods using this attribute

[WebGet(UriTemplate = "users/{username}")]

here is a sample method from msdn

[WebGet(UriTemplate = "users/{username}")]
[OperationContract]
User GetUserAccount(string username)
{
    if (!IsUserAuthorized(username))
    {
        WebOperationContext.Current.OutgoingResponse.StatusCode =
            HttpStatusCode.Unauthorized;
        return;
    }
    User user = FindUser(username);
    if (user == null)
    {
        WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
        return null;
    }
    return user;
}


回答2:

In MVC3, the Request object is available in the controller, with the content of the body being available in the InputStream object. This code worked for me:

        this.Request.InputStream.Position = 0;
        var xmlContent = new System.IO.StreamReader(this.Request.InputStream).ReadToEnd();

Hope that helps.