ajax 使用 MVC 4 API 控制器 POST JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12446024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:50:57  来源:igfitidea点击:

POST JSON with MVC 4 API Controller

ajaxasp.net-mvcasp.net-mvc-4asp.net-web-api

提问by user1615362

I have this code:

我有这个代码:

   $.ajax({


        type: "POST",
        url: "/api/slide",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: '{"Title":"fghfdhgfdgfd"}',
        dataType: "json",

An this is my controler:

这是我的控制器:

public class SlideController : ApiController
{

    // POST /api/Slide
    public void Post(string Title)
    {
    }

When I run the code and call the /api/Slide, the [Title] has no data and is null.

当我运行代码并调用 /api/Slide 时,[Title] 没有数据并且为空。

How do I post JSON to the API controller?

如何将 JSON 发布到 API 控制器?

POST http://127.0.0.2:81/api/slide HTTP/1.1
Host: 127.0.0.2:81
Connection: keep-alive
Content-Length: 18
Origin: http://127.0.0.2:81
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://127.0.0.2:81/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Title=fghfdhgfdgfd

回答by Darin Dimitrov

Define a view model:

定义视图模型:

public class SlideViewModel
{
    public string Title { get; set; }
}

then have your controller action take this view model as argument:

然后让您的控制器操作将此视图模型作为参数:

public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post(SlideViewModel model)
    {
        ...
    }
}

finally invoke the action:

最后调用动作:

$.ajax({
    type: 'POST',
    url: '/api/slide',
    cache: false,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ title: "fghfdhgfdgfd" }),
    success: function() {
        ...    
    }
});

The reason for that is that simple types such as strings are bound from the URI. I also invite you to read the following articleabout model binding in the Web API.

原因是像字符串这样的简单类型是从 URI 绑定的。我还邀请您阅读以下有关 Web API 中模型绑定的文章

回答by Isioma Nnodum

Ensure the object you are trying to convert to has a default (empty) constructor.

确保您尝试转换为的对象具有默认(空)构造函数。

Rule of thumb: If you want to deserialize to an object, you need to make it simple for the objects to be created. These guidelines can help:

经验法则:如果要反序列化为对象,则需要使要创建的对象变得简单。这些指南可以帮助:

  • All properties that are to be passed around must be public

  • the object needs to able to be constructed without any parameters.

  • 所有要传递的属性必须是公共的

  • 该对象需要能够在没有任何参数的情况下构建

This JSON string/object for example:

这个 JSON 字符串/对象例如:

{ Name: "John Doe", Phone: "123-456-7890", Pets: [ "dog", "cat", "snake" ] }

can be converted to an object from the following class:

可以从以下类转换为对象:

 public class Person {

     public string Name { get; set; }
     public string Phone { get; set; }
     public string[] Pets { get; set; }

  }

or this one:

或者这个:

public class Person {

   public string Name { get; set; }
   public string Phone { get; set; }
   public string[] Pets { get; set; }
   public Person() {}
   public Person(string name, string phone) {
      Name = name;
      Phone = phone;
   }

}

or this one:

或者这个:

public class Person {

    public string Name { get; set; }
    public string Phone { get; set; }
    public string[] Pets { get; set; }
    public Person() {}


 }

but not this one

但不是这个

public class Person {

    public string Name { get; set; }
    public string Phone { get; set; }
    public string[] Pets { get; set; }
    public Person(string name, string phone) {
      Name = name;
      Phone = phone;
    }

}

Now let ASP.NET MVC 4 do the rest

现在让 ASP.NET MVC 4 做剩下的事情

public class PersonController : ApiController
{
        // .. other actions 
        public HttpResponseMessage PostPerson(Person person)
        {
            if ( null != person)
                // CELEBRATE by doing something with your object
            else 
                // BE SAD and throw and exception or pass an error message

        }
        // .. other actions 
}

If your class cannot have a default constructor or if you don't have access to the source code for the class, you can create an adapter class that

如果您的类没有默认构造函数或者您无权访问该类的源代码,您可以创建一个适配器类

  • has a default constructor
  • exposes those properties that need to be public
  • 有一个默认构造函数
  • 公开那些需要公开的属性

Using the Person class above with no default constructor, an adapter could look like

使用上面没有默认构造函数的 Person 类,适配器看起来像

public class PersonAdapter {

    public Person personAdaptee;

    public string Name {
        get { return personAdaptee.Name; }
        set { personAdaptee.Name = value }
    }

    public string Phone {
        get { return personModel.Phone; }
        set { personModel.Phone = value; }
    }

    public string[] Pets {
        get { return personAdaptee.Pets; }
        set {personAdaptee.Pets = value }
    }

    public PersonAdapter() {

        personAdaptee = new Person("", "", null);

    }

}

Now let ASP.NET MVC 4 do the rest

现在让 ASP.NET MVC 4 做剩下的事情

public class PersonController : ApiController
{
        // .. other actions 
        public HttpResponseMessage PostPerson(PersonAdapter person)
        {
            if ( null != person)
                // CELEBRATE by doing something with your object
            else 
                // BE SAD and throw and exception or pass an error message

        }
        // .. other actions 
}

回答by Steve Lydford

Try this:

尝试这个:

$.ajax({
    type: "POST",
    url: "/api/slide",
    data: { Title: "fghfdhgfdgfd" }
});

It is the quotes around the data attribute which are causing this:

导致这种情况的是 data 属性周围的引号:

i.e >> data: { Title: "fghfdhgfdgfd" }
not >> data: '{ Title: "fghfdhgfdgfd" }'

即>>数据:{标题:“fghfdhgfdgfd”}
不是>>数据:'{标题:“fghfdhgfdgfd”} '

UPDATE:
Also your controller seems a little strange, although it is hard to tell without seeing your routing, etc.

更新:
此外,您的控制器似乎有点奇怪,尽管在没有看到您的路由等的情况下很难判断。

I would expect to see something more like this:

我希望看到更像这样的东西:

public class SlideController : ApiController
{
    public HttpResponseMessage PostSlide(string Title)
    {
        // Do your insert slide stuff here....

        string uri = Url.Link("DefaultApi", new { id = item.Id });
        response.Headers.Location = new Uri(uri);
        return response;
    }
}

Clearly, you will also need to update the URL in your jQuery too.

显然,您还需要更新 jQuery 中的 URL。

Take a look here:

看看这里:

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

ANOTHER UPDATE:

另一个更新:

It would be usual to create a CLR object to match your Json and use the MVC model binder to bind directly to that. If you don't want to do that you can bind to an object and deserialize into a Dictionary:

通常创建一个 CLR 对象来匹配您的 Json 并使用 MVC 模型绑定器直接绑定到它。如果您不想这样做,您可以绑定到一个对象并反序列化为一个字典:

// POST api/values
public void Post(object json)
{
    Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json.ToString());
    var x = values["Title"];
}

回答by Bilal Saeed

Cast the action parameter to FromBody i.e:

将动作参数投射到 FromBody 即:

public class SlideController : ApiController
{

    // POST /api/Slide
    public void Post([FromBody]string Title)
    {
    }
}

回答by Ghebrehiywet

$.ajax({
    type: 'POST',
    url: '/api/slide',
    cache: false,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ title: "fghfdhgfdgfd" }),
    success: function() {
        ...    
    }
});

Controller is

控制器是

public class SlideController : ApiController
{

    // POST /api/Slide
    public void Post(string Title)
    {
    }

Your url is not valid, url must address the action Postin Slidecontroller

您的网址是无效的,URL必须解决的动作滑动控制器

edit your url to url:"~/ControllerName/ActionName" in this context must be Url:"~/Slide/Post"

将您的 url 编辑为 url:" ~/ControllerName/ActionName" 在这种情况下必须是Url:"~/Slide/Post"