3

I'm using Vue.js and I'm trying to make post request and send data { name: 'TestName' } to controller, but when I hit controller, instead name to be equal to "TestName" it's null.

This is my Fetch: post request

   `sendName() {
        let url = 'https://localhost:44362/Home/ReceiveName'
        fetch(url, {
            method: 'POST',
            body: JSON.stringify({ name: 'TestName' })
        }).then(function (response) {
            response
        }).catch(err => {
            err
        });
    }`

And this is my action method ReceiveName in the HomeController

 `[HttpPost]
    public string ReceiveName(string name)
    {
        *some code*
    }`

Here name must be "TestName", but it's NULL

I had tried answers from this question How to pass data to controller using Fetch api in asp.net core , to set [FromBody] in ReceiveName method like this public string ReceiveName( [FromBody] string name), but it doesn't worked for me. Then I tried to add headers to fetch body

`headers: {
  'Content-Type': 'application/json'
},`

But when i do this i get that error in browser

Failed to load https://localhost:44362/Home/ReceiveName: Response for preflight does not have HTTP ok status.

I think it's because CORS rules.

I'm running my backend on https://localhost:44362 and my frontend on http://localhost:8080/ so I had to edit my CORS rules in web.config like this

 `<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
  </httpProtocol>`

My question is - How can I receive my data from Fetch:post to my action method?

Is there a need to make query string?

But I don't want to send my string "TestName" as FormData I know that if I send it like that I will receive it in my action method, but is this is a good way to send a string?

3 Answers 3

4

I'm ran into a similar issue and found a solution to my problem. I think you may need to define a model class with a name property, and then add [FromBody] to your action parameter.

Create a model class...

public class SomeModel
{
    public string name { get; set; }
}

Then use that model as your parameter type...

[HttpPost]
public string ReceiveName([FromBody]SomeModel model)
{
    // model.name should contain the value.
}

I'm not a fan of this solution, but it's the best I could find through my researching. Hope it helps you!

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

1 Comment

Spent a lot of time trying to figure this out. Didn't realize I had to create a model class for it. Thanks!
1

Unfortunately .NET MVC doesn't include the [FromBody] attribute (it is only available in Web API or .NET Core). In order to access the information in the body of a post, you can use the HttpRequestBase.InputStream property of Controller.Request.

Here is an example (this code uses Newtonsoft to deserialize the json object in the body of the request).

[HttpPost]
public ActionResult ReceiveName()
{
    System.IO.Stream request = Request.InputStream;
    request.Seek(0, SeekOrigin.Begin);
    string bodyData = new StreamReader(request).ReadToEnd();
    var data = JsonConvert.DeserializeObject<SomeType>(bodyData);

    //do something
    return Json(new { success = true});
}

Comments

1

async function postData() {
    var data="abc";
    // Default options are marked with *
    const response = await fetch("https://localhost:44334/api/Blog/", {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      redirect: 'follow', // manual, *follow, error
      referrer: 'no-referrer', // no-referrer, *client
      body: JSON.stringify(data) // body data type must match "Content-Type" header
    });
  }

    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

Set value into var data. JSON.stringify(data). <3

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.