如何将查询字符串与 WCF 服务一起使用?

How can I use a query string with a WCF Service?

我正在尝试创建 Web 服务,到目前为止它们运行良好,但我遇到了一个问题:如果我的查询字符串与我指定的顺序不一致,代码给我错误的结果。

在开始一个大项目之前,我希望能够传入一个查询字符串,这样顺序就无关紧要了——传入“?user=foo&pass=bar”应该等同于“?pass= bar&user=foo",但我只是不确定如何让它按预期工作。

实际上,我不会因更改查询字符串参数而出现错误,而是 DBAgent.authenticate() 只会按顺序接受参数,而不管查询字符串中的参数名称如何。

我错过了什么?

IDBAgent.cs:

public interface IDBAgent
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/authenticate/?username={username}&password={password}", Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    string authenticate(string username, string password);
}

DBAgent.svc.cs

public class DBAgent : IDBAgent
{
    public string authenticate(string username, string password)
    {
        return runSQL("EXEC sp_Authenticate '" + username + "', '" + password + '\'');
    }
}

index.html:

var output = "";
function callService(url, params)
{
    try {
        return $.ajax({
            type: "GET",
            async: false,
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processdata: true,
            success: function (msg) {
                output = msg;
            },
            error: function(){console.log("Oops.")}
        });
    }
    catch (e) {
        console.log("Something went wrong! (╯°□°)╯︵ ┻━┻");
    }
}

function authenticate(user, pass)
{
    callService("http://localhost/DBAgent.svc/authenticate/?username=foo&password=bar", []).done();    // Returns true
    console.log(output);
    callService("http://localhost/DBAgent.svc/authenticate/?password=bar&username=foo", []).done();    // Returns false
    console.log(output);
    callService("http://localhost/DBAgent.svc/authenticate/?password=foo&username=bar", []).done();    // Returns true
    console.log(output);
}

对于这种情况,您可能应该考虑使用 'POST' 而不是 'GET'。另外请注意,使用 UriTemplate 时查询字符串参数的顺序无关紧要。 ?user=foo&pass=bar" 在结构上等同于 "?pass=bar&user=foo",