mskuratowski
mskuratowski

Reputation: 4124

Angular2 http post couln't catch controller action

I would like to call post asp net core controller action.

Here's my code: Message Controller

[Route("api/[controller]")]
public class MessageController : Controller
{
    [HttpPost]
    public IActionResult AddBlog(string email)
    {
        //test
        return View();
    }
}

my form:

<form [formGroup]="contactForm" (ngSubmit)="onSubmitModelBased()">
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email" formControlName="email" placeholder="email">
    </div>
    <button type="submit" class="btn btn-block btn-primary">Wyślij</button>
</form>

and my component ts

public onSubmitModelBased() {
    alert("test");
    let body = JSON.stringify({ email: '[email protected]' });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http
        .post('/api/Message/AddBlog', body, { headers: headers })
        .subscribe(data => {
            alert('ok');
        }, error => {
            alert('not ok');
        });
}

I; seeing alert("test") and the http.post action return alert('ok'). I've also made a breakpoint in controller action but it hasn't been catched there.

Upvotes: 1

Views: 536

Answers (1)

juunas
juunas

Reputation: 58743

Your routing should be:

[Route("api/[controller]/[action]")]
public class MessageController : Controller
{
    [HttpPost]
    public IActionResult AddBlog([FromBody] AddBlogModel model)
    {
        //test
        return View();
    }
}

The way you have it set up now means the action is hit when a POST request comes to /api/message. Adding the action placeholder makes it accept POST requests to /api/message/addblog as you intended.

EDIT: As for your other problem, you are sending a JSON object but expecting MVC to figure it out. You will need to make a model class such as:

public class AddBlogModel
{
    public string Email { get; set; }
}

And change your controller action as above. This will tell MVC Core that the model should be created based on the request body, which is your JSON. The model contains a single property that will contain the email address.

Upvotes: 3

Related Questions