0

I have this method in a controller in a web api

public class UserController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Login(string name, string password){
        //dothings
    }
}

but if I try a ajax request:

$.ajax({
    type: "POST",
    url: "http://localhost:19860/Api/User/Login",
    data: { name: "name", password: "12345" },
    success: succ,
    error: err
});

It gives me the error:

Message: "No HTTP resource was found that matches the request URI 'http://localhost:19860/Api/User/Login'." MessageDetail: "No action was found on the controller 'User' that matches the request."

but, if i remove the parameters it works!

public class UserController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Login(){
        string name=  HttpContext.Current.Request.Params["name"];
        string password= HttpContext.Current.Request.Params["password"];
        // name and password have the value that i passed in the ajax call!!
    }
}

why it is like this?

For reasons unrelated to this question, I can't change the web api, so I have to mantain the:

public HttpResponseMessage Login(string name, string password)

format.

Can I mantain this format and be able to make the ajax call?

1 Answer 1

1

You can not post multiple parameter to Web-API methods as mentioned in this blog post

There is few alternative to this as follow.

1. Try to pass it on queryString.

Change your ajax function call like below.

$.ajax({
    type: "POST",
    url: "http://localhost:19860/Api/User/Login?name=name&pass=pass",
    data: { name: "name", password: "12345" },
    success: succ,
    error: err
});

you will get name = name and password = pass in your api controller.

2. Create your own binder as implemented in this blog post.

3. Wrap all the Web-API method parameter in one object or type (recommended).

From the above you can use 1st and 2nd approach as you mentioned in your question you can not change your api method signature.

Sign up to request clarification or add additional context in comments.

2 Comments

@AlbertCortada Welcome Just Note: passing credential over url is not good practise so I would suggest to go with third option if possible for you.
Right now it's not possible to me, but I will take this into consideration in upcoming code reviews

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.