how get html post data and pass to a webservice?

2019-06-14 15:05发布

问题:

I have some knowledge on using WCF, but I don't know how to construct it and be able to receive data from HTML-POST.
Inside my sample Html is this:

<html>
<body>
    <form method="POST" action="#">
        Name:   <input type="text" id="txtName" value="" /><br />
        Age:    <input type="text" id="txtAge" value="" /><br />
        Address:<input type="text" id="txtAddress" value="" /><br />
        <input type="submit" value="Send" />
    </form>
</body
</html>  

And inside my WCF is:

namespace WCF
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class User
    {
        WebInvoke(UriTemplate = "", Method = "POST")]
        public DataFromHTMLPost(UserData instance)
        {
            throw new NotImplementedException();
        }
    }
}

Can anyone give some suggestion on how could I pass the data from HTML-POST to webservice?
Or give me some links as reference. Thanks a lot!

回答1:

You will need to grab the data from code behind and then pass it through to the web service.

You can either add runat="server" to each of those input fields and get the data directly by going

txtName.Text

or you can get all the posted data by

NameValueCollection nvc = Request.Form; 

String name = nvc["txtName"];

Then just call the web service which I would assume you have added as a Service Reference in your project?

UPDATE (Since learning its a PHP client accessing .NET WCF)

For getting post data do this:

$item = $_POST['item'];

item is the name of the input field.

PHP code to connect to WCF (using JSON)

  /**
    * @param $service name of JSON service to call
    * @return string url in string
    */
  function request_Url( $service )
{

return 'http://api.domain.com/api.svc'.'/'.$service

}

/**
 * 
 * @return array|false Contest List or false on failure
 */
function get_contestList() {

    $jsonStr = json_decode(file_get_contents($this->request_Url('MethodName')), TRUE);

    return $jsonStr;
}

In the WCF you will need to change your method signatures to

[OperationContract]    
[WebGet(ResponseFormat = WebMessageFormat.Json, 
        RequestFormat = WebMessageFormat.Json,               
        UriTemplate = "/MethodName")]
public String MethodName()
{

}


标签: c# html wcf rest