带有多个参数的Json Post请求

时间:2012-12-16 13:42:33

标签: jquery c asp.net-web-api

当我使用POST请求在C#WebApi下面调用时。当我在方法中有一个参数时它工作正常。假设我想要包含另一个参数public HttpResponseMessage Post(Member member, bool IsAdmin),那么data: { id: 2012, firstName: 'FirstNameValue', lastName: 'LastNameValue' }会有什么价值?

C#

public HttpResponseMessage Post(Member member)
    {
        try
        {
            var id = BusinessModule.PostMember(member);
            member.Id = id;
            var response = Request.CreateResponse<Member>(HttpStatusCode.Created, member);
            response.Headers.Location = new Uri(VirtualPathUtility.AppendTrailingSlash(Request.RequestUri.ToString()) + member.Username);
            return response;
        }
        catch (MemberException e)
        {
            var response = new HttpResponseMessage(HttpStatusCode.Conflict);
            response.Content = new StringContent(e.Message);
            throw new HttpResponseException(response);
        }
    }

Jquery的

 function postMember() {
            $.ajax({
                url: baseAddress,
                type: "POST",
                // Firefox reuires the dataType otherwise the "data" argument of the done callback
                // is just a string and not a JSON 
                dataType: 'jsonp',
                accept: "application/json",
                data: { id: 2012, firstName: 'FirstNameValue', lastName: 'LastNameValue' },
            })
            .done(function (data) {
                $("#membersList").append('<li data-member=\'' + JSON.stringify(data) + '\'>' + data.firstName + ' ' + data.lastName + '</i>');
            })
            .fail(function (e) {
                alert(e.statusText);
            })
            .always(function () { });
        }

1 个答案:

答案 0 :(得分:0)

似乎Web API不处理多个发布的内容值。

请参阅here解释和可能的解决方法。 我将新参数放在查询字符串中,在API方法中将从QueryString中读取变量。

所以,在 JQUery 中你会有下一行:

url: baseAddress+"?IsAdmin=true",

C#将是:

bool IsAdmin = Convert.ToBoolean(queryItems["IsAdmin"]);