1

I cannot post a simple string value to my WebApi and I get a 415 error. What's the correct syntax to make this happen? Thanks!

createRole(name: string) {
    var fullUri = this.baseUri;
    fullUri += 'api/role/CreateRole';

    return this.http.post(fullUri, name);
}
[HttpPost("CreateRole")]
public async Task<IActionResult> CreateRoleAsync([FromBody]string name)
{
    //...

}
2
  • 1
    Is the solution marked as answer in this thread helpful? Commented Apr 20, 2020 at 7:25
  • Yes this ended up working for me but I was hoping to avoid this approach since it's just one single property. Thanks for sharing though! Commented Apr 20, 2020 at 17:03

3 Answers 3

1

Use [FromForm] attribute instead of [FromBody] attribute. And apply [ApiController] attribute to your controller.

[HttpPost("CreateRole")]
public async Task<IActionResult> CreateRoleAsync([FromForm]string name)
{
    //...

}

It will work if you post name as FormData or using Form tag. Because [FromForm] gets values from posted form fields.

Another solution is post name as object and make a model / DTO

public class SaveModel 
{
   public string Role {get; set;}
}
[HttpPost("CreateRole")]
public async Task<IActionResult> CreateRoleAsync([FromBody] SaveModel model)
{
    //...

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

5 Comments

name comes in as null when I use [FromForm]
@roonz11 I have edited my answer. Please check and let me know if it works.
Yes I ended up wrapping my string property in a DTO to get it to work but I was hoping to not have to do this since it's just one single property. How would I modify my code to post it as FormData? Thanks!
In your method change to createRole() { var fullUri = this.baseUri; fullUri += 'api/role/CreateRole'; var formData: any = new FormData(); var role = "test"; formData.append("name", role); return this.http.post(fullUri, formData); }
Sorry for the late reply. This approach worked. Cheers!
0

You can use FromForm as @4L4M1N's answer like this

Angular :

createRole(name: string) {
    var fullUri = this.baseUri;
    fullUri += 'api/role/CreateRole';
    
var formData = new FormData()
    formData.append("name",name)

    return this.http.post(fullUri, name);
}

C# :

[HttpPost("CreateRole")]
public async Task<IActionResult> CreateRoleAsync([FromForm]string name)
{
    //...

}

Comments

-1

A little tweak in api

 [HttpPost]
            [Route("api/role/CreateRole")]
            public int Post([FromBody] string name)
            {
               //logic...
            }

Comments

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.