开发者

WCF WebInvoke with query string parameters AND a post body

开发者 https://www.devze.com 2023-04-10 02:11 出处:网络
I\'m fairly new to web services and especially WCF so bear with me. I\'m writing an API that takes a couple of parameters like username, apikey and some options, but I also need to send it a string w

I'm fairly new to web services and especially WCF so bear with me.

I'm writing an API that takes a couple of parameters like username, apikey and some options, but I also need to send it a string which can be a few thousands words, which gets manipulated and passed back as a stream. It didn't make sense to just put it in the query string, so I thought I would just have the message body POSTed to the service.

There doesn't seem to be an easy way to do this...

My operation contract looks like this

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate="Method1?email={email}&apikey={apikey}"+
"&text={text}&quality={qual}", BodyStyle = WebMessageBodyStyle.Bare)]
Stream Method1(string email, string apikey, string text, string qual);

And this works. But it is the 'text' parameter I want to pull out and have in the post body. One thing I read said to have a stream as another parameter, like this:

Stream Method1(string email, string apikey, string qual, Stream text);

which I could then read in. But that throws an error saying that if I want to have a stream parameter, that it has to be the only parameter.

So how can I achieve what I am trying to do here, or is it no big deal to send up a few thousand words in the query string开发者_StackOverflow?


https://social.msdn.microsoft.com/Forums/vstudio/en-US/e2d074aa-c3a6-4e78-bd88-0b9d24b561d1/how-to-declare-post-parameters-in-wcf-rest-contract?forum=wcf

Best answer I could find that tackles this issue and worked for me so I could adhere to the RESTful standards correctly


A workaround is to not declare the query parameters within the method signature and just manually extract them from the raw uri.

Dictionary<string, string> queryParameters = WcfUtils.QueryParameters();
queryParameters.TryGetValue("email", out string email);


// (Inside WcfUtils):

public static Dictionary<string, string> QueryParameters()
{
    // raw url including the query parameters
    string uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

    return uri.Split('?')
        .Skip(1)
        .SelectMany(s => s.Split('&'))
        .Select(pv => pv.Split('='))
        .Where(pv => pv.Length == 2)
        .ToDictionary(pv => pv[0], pv => pv[1].TrimSingleQuotes());
}

// (Inside string extension methods)

public static string TrimSingleQuotes(this string s)
{
    return (s != null && s.Length >= 2 && s[0] == '\'' && s[s.Length - 1] == '\'')
        ? s.Substring(1, s.Length - 2).Replace("''", "'")
        : s;
}


Ended up solving simply by using WebServiceHostFactory

0

精彩评论

暂无评论...
验证码 换一张
取 消