简体   繁体   中英

How to send data over POST without URI in WCF rest services

I am new to WCF. I am trying to implement a restful service for authentication.

My WCF Code is as below.

    [OperationContract]
    [WebInvoke(Method="POST", UriTemplate = "auth", RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped)]
    Employee authEmployee(String username, String password);

What I need to do here is get username and password without receiving it via URL. How do I achieve this?

This might be a basic question for experts, but I am new to this. Any help is appreciated.

Thanks.

I'll rewrite my comments here for clarity.

Your client side should call service method by creating request and setting properly request fields, for example

HttpWebRequest req =(HttpWebRequest)HttpWebRequest.Create(uri);

req.Method = "Post"; 
req.ContentType = "application/json";
byte[] bodyBytes = Encoding.UTF8.GetBytes("{\"Name\":\"John Doe\",\"Age\":33}");

req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);  
req.GetRequestStream().Close();

and of course

resp = (HttpWebResponse)req.GetResponse();

in that way consumer has to pass values but that values do not travel directly through url

I think that method name is passed in URI and only attributes that this method needs are passed inside json.

{ "action": "Authenticate", "attributes": { "AccountName": "admin", "Password": "password" } }. This is how client is sending data. So should I have 3 arguments in my service method? for Action, AccountName and Password?

In this case your service operation should look like this:

Employee authEmployee(string action, attributes attr);

Define the attributes type as:

class attributes
{
    string AccountName { get; set; }
    string Password { get; set; }
} 

As a side note, it's not particularly secure if you're passing credentials in as plaintext in this manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM