0

I have this jQuery call:

jQuery.ajax({
            type: "POST",
            url: "http://localhost:5832/api/Login/Post",
            data: JSON.stringify({ username: 'user12', password: '1234' }),
            contentType: "application/json; charset=utf-8", 
            dataType: "json",
            success: function (data) {
                alert(data.d);
            }
        });

Which calls this web api controller action:

[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage Post(string username, string password)
{
    string authenticationToken = "";
    authenticationToken = hpl.LoginUser(username, password);
    //Some other code

    return Request.CreateResponse(HttpStatusCode.OK, authenticationToken);
}

I'm trying to submit the parameters with the data attribute but the call is not triggered.

When I'm changing the url to: http://localhost:5832/api/Login/Post?username=1&password=2

I'm able to reach the controller action.

How I can pass the parameters as part of the data attribute of the jquery call instead of query string params?

1
  • Just use: data: { username: "user12", password: "1234" },
    – Hackerman
    Commented May 27, 2016 at 18:08

1 Answer 1

0

ASP.Net Web API does not support multiple parameters inside the body of the request.

You can only send one single parameter using the FromBody attribute, so instead of multiple parameters just use a single object which contains any property you need:

public class LoginModel {
    public string username { get; set; }

    public string password { get; set; }
}

[System.Web.Http.HttpPost]
public HttpResponseMessage Post([FromBody] LoginModel loginModel)
{
    string authenticationToken = "";
    authenticationToken = hpl.LoginUser(loginModel.username, loginModel.password);
    //Some other code

    return Request.CreateResponse(HttpStatusCode.OK, authenticationToken);
}

As an aside: AcceptVerbs("POST") and HttpPost attributes are redundant, use one of them but not both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.