简体   繁体   English

Vue 获取 post 数据到控制器 asp.net mvc

[英]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.我正在使用 Vue.js 并且我正在尝试发出发布请求并将数据 { name: 'TestName' } 发送到控制器,但是当我点击控制器时,名称等于“TestName”,它为空。

This is my Fetch: post request这是我的 Fetch:发布请求

   `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这是我在 HomeController 中的操作方法 ReceiveName

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

Here name must be "TestName", but it's NULL这里 name 必须是“TestName”,但它是 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.我已经尝试过这个问题的答案How to pass data 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) ,但它不起作用我。 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.无法加载https://localhost:44362/Home/ReceiveName :预检响应没有 HTTP ok 状态。

I think it's because CORS rules.我认为这是因为 CORS 规则。

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我在https://localhost:44362上运行我的后端,在http://localhost:8080/上运行我的前端,所以我不得不像这样在 web.config 中编辑我的 CORS 规则

 `<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?我的问题是- 如何从 Fetch:post 接收我的数据到我的操作方法?

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?但我不想将我的字符串“TestName”作为FormData发送我知道,如果我这样发送它,我将在我的操作方法中收到它,但这是发送字符串的好方法吗?

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.我认为您可能需要定义一个具有name属性的模型类,然后将 [FromBody] 添加到您的操作参数中。

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).不幸的是 .NET MVC 不包括 [FromBody] 属性(它仅在 Web API 或 .NET Core 中可用)。 In order to access the information in the body of a post, you can use the HttpRequestBase.InputStream property of Controller.Request .为了访问帖子正文中的信息,您可以使用Controller.RequestHttpRequestBase.InputStream属性。

Here is an example (this code uses Newtonsoft to deserialize the json object in the body of the request).这是一个示例(此代码使用Newtonsoft反序列化请求正文中的 json 对象)。

[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.将值设置为 var 数据。 JSON.stringify(data). JSON.stringify(数据)。 <3 <3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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