【问题标题】:Using JSON as a parameter for WCF Restservice Method使用 JSON 作为 WCF Restservice 方法的参数
【发布时间】:2011-08-08 14:38:29
【问题描述】:

希望您能提供帮助,我正在尝试升级损坏的登录系统,以便在传输登录凭据时使用 POST 而不是 GET。

它永远不会到达实际的方法,所以问题出在界面和我的 javascript 之间。

界面:

[OperationContract]
        [WebInvoke(Method = "POST", 
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, 
            UriTemplate = "/DoLogin")]
        LoginKey DoLogin(string email, string password,string tenant);

Javascript:

 $.ajax({
            type: "POST",
            url: "RestService.svc/DoLogin",
            data:'{"email":"' + encodeURIComponent(email) + '","password":"' + encodeURIComponent(password) + '","tenant":"' + encodeURIComponent(tenant) + '"}',
            dataType: "json",
            cache: false,
            success: function (loginKey) {
... rest of method

我发送的 JSON 数据是有效的: { “电子邮件”:“邮件”, "密码": "某个密码", “租户”:“租户” } 任何想法这里出了什么问题?它与 GET 一起工作得很好

ps这里是实际登录rest服务方法的第一行:

public LoginKey DoLogin(string email, string password, string tenant)
        {

【问题讨论】:

  • 你能发布你遇到的错误吗?
  • 另外,请发布您的 WCF 服务配置。

标签: javascript .net wcf json rest


【解决方案1】:

也尝试设置内容类型,以防万一:

类型:“POST”,
url: "RestService.svc/DoLogin", 数据:'{"email":"' + encodeURIComponent(email) + '","password":"' + dataType:“json”,
“contentType”:“application/json; charset=utf-8”, ...

除此之外,您的代码看起来是正确的,尽管我更喜欢不同的方法:

public class Credential
{
  public string Email{get;set;}
  public string Password {get;set;}
  public string Tenant {get;set;}
}

在你的 WCF 方法中:

public LoginKey DoLogin(Credential theCredential)

在你的标记中:

var theCreadential = new Object();
theCreadential.Email = $('#txtEmail').val();
theCreadential.Password = $('#txtPassword').val();
theCreadential.Tenant = $('#txtTenant').val();
 $.ajax({
            type: "POST",
            url: "RestService.svc/DoLogin",
            data: "{'theCredential': " + JSON.stringify(theCredential) + "}",
            dataType: "json",
            cache: false,
            success: function (loginKey) {
... rest of method

【讨论】:

  • 谢谢,ContentType 成功了。一个更好的 JSON 对象“美化”了它 :)
【解决方案2】:

我决定放弃整个 restservice,而是将项目迁移到 MVC3,它可以更简单、更轻松地处理这些场景。

通过在 ajax 调用 btw 中添加 contentType 解决了这个问题:

 $.ajax({
            type: "POST",
            url: "restservice.svc/dologin",
            data: JSON.stringify(json),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (result) {

【讨论】:

    猜你喜欢
    • 2012-04-22
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多