简体   繁体   中英

Vue fetch post data to controller asp.net mvc

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?

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!

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});
}

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM