【问题标题】:How can I use a query string with a WCF Service?如何将查询字符串与 WCF 服务一起使用?
【发布时间】:2015-09-23 23:38:01
【问题描述】:

我正在尝试创建 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);
}

【问题讨论】:

  • 哎呀,您要求进行 sql 注入。 GET 对于身份验证也不是一个好主意。
  • 我一直在创造一个科学怪人的代码怪物,拼凑 sn-ps 并学习它们是如何工作的。我没有转换为 POST 或防止 SQL 注入;我认为这是在我得到一些准系统工作之后发生的 =/

标签: c# wcf query-string


【解决方案1】:

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

【讨论】:

  • 当你说“顺序无关紧要”时,我有点困惑——我的 js 代码显示了我正在使用的确切代码,但身份验证是按照参数出现的顺序抓取参数(不管他们面前的标签)。 "?user=foo&pass=bar" 和 "?pass=foo&user=bar" 评估为相同的值。
  • 我不确定到底发生了什么,但是在玩了一段时间之后,这行得通。可能是 PEBKAC,但谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2011-03-28
相关资源
最近更新 更多