1

当我使用 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 () { });
        }
4

1 回答 1

0

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

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

因此,在JQUery中,您将拥有下一行:

url: baseAddress+"?IsAdmin=true",

C#中将是:

bool IsAdmin = Convert.ToBoolean(queryItems["IsAdmin"]);
于 2012-12-16T14:55:49.897 回答