Angular2 Http post request not binding to ASP.NET 5 controller's action

后端 未结 3 1127
醉梦人生
醉梦人生 2020-12-21 08:31

I am initiating a post request from Angular2 to a ASP.NET 5 controller action. Angular is posting the data correctly and hitting the controller action but it is not being ma

相关标签:
3条回答
  • 2020-12-21 08:46

    In this case you don't require to pass the header. look at here. you may try this.

    this.http.post('/api/ControllerName/DemoAction?firstName=Ali')
    .subscribe(
                    (data) => {
                        console.log('Response received');
                        console.log(data);
                    },
                    (err) => { console.log('Error'); },
                    () => console.log('Authentication Complete')
                );
    

    This will surely work.


    Edited:

    Figured out your problem.

    First: When you are receiving paramter(s) at API end , you must use above portion.

    second: When you are receiving object at API end, you must use below code.

    I'm showing you with my setup as I don't know your object at server side.

    let um=JSON.stringify({ Username: "Hello1",Password:"Hello2"});
    
    let headers = new Headers({ 'Content-Type': 'application/json'});
    
    this.http.post(this.url+'/Authentication',um,{ headers: headers })
                            .subscribe(...);
    

    At server side I have following setup.

    public class UserModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    
    [HttpPost]
    public IHttpActionResult Authentication(UserModel um)  // I m getting value here.
    {
        if (um.Username == "a" && um.Password == "a")
        {
            um.Username = um.Username;
            um.Password = um.Password;
            return Ok(um);
        }
        return NotFound();
    }
    

    Simple solution !! isn't it?

    0 讨论(0)
  • 2020-12-21 08:56

    For me it works:

    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http.post(this.url, JSON.stringify({ firstName: 'Ali' }), { headers: headers })
    
    0 讨论(0)
  • 2020-12-21 09:09

    You try to send a JSON content (created using the JSON.stringify method) with a content type url encoded form.

    You should try to use the application/json one:

    let body = JSON.stringify({ firstName: 'Ali' });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    
    this.http.post(this.url, body, { headers: headers })
    

    Edit

    If you want to provide a form content, you could leverage the URLSearchParams class:

    var params = new URLSearchParams();
    params.set('firstName', 'Ali');
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    
    this.http.post(this.url, params.toString(), { headers: headers })
    
    0 讨论(0)
提交回复
热议问题