使用MVC 4 API控制器POST POST JSON

use*_*362 17 ajax asp.net-mvc asp.net-mvc-4 asp.net-web-api

我有这个代码:

   $.ajax({


        type: "POST",
        url: "/api/slide",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: '{"Title":"fghfdhgfdgfd"}',
        dataType: "json",
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

public class SlideController : ApiController
{

    // POST /api/Slide
    public void Post(string Title)
    {
    }
Run Code Online (Sandbox Code Playgroud)

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

如何将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
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 21

定义视图模型:

public class SlideViewModel
{
    public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post(SlideViewModel model)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

最后调用动作:

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

原因是从URI绑定了诸如字符串之类的简单类型.我还邀请您阅读以下有关Web API中模型绑定的文章.

  • 它是RESTful和传统的.您在jQuery请求中使用POST动词=>调用Post动作.如果您使用了`GET`动词(例如直接在浏览器地址栏中键入动作名称)=>将调用Get动作.所以你不能有数百个.标准的HTTP动词是`GET`,`POST`,`PUT`和`DELETE`,所以这些是你应该使用的动作名称.当然,您总是可以违反标准RESTful约定=>继续并修改`〜/ App_Start/WebApiConfig.cs`文件中的路由,以便在URL中包含操作名称. (2认同)
  • 当然,这是有区别的.`JSON.stringify`方法生成您正在发送的javascript变量的JSON编码字符串.如果你只使用`{title:"fghfdhgfdgfd"}`那么jQuery就不再发送JSON编码的字符串了.它正在使用`application/x-www-form-urlencoded`请求,这就是为什么你应该在这种情况下删除`contentType:'application/json'`设置. (2认同)

Isi*_*dum 10

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

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

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

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

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

{ Name: "John Doe", Phone: "123-456-7890", Pets: [ "dog", "cat", "snake" ] }
Run Code Online (Sandbox Code Playgroud)

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

 public class Person {

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

  }
Run Code Online (Sandbox Code Playgroud)

或者这个:

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

}
Run Code Online (Sandbox Code Playgroud)

或者这个:

public class Person {

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


 }
Run Code Online (Sandbox Code Playgroud)

但不是这个

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

}
Run Code Online (Sandbox Code Playgroud)

现在让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 
}
Run Code Online (Sandbox Code Playgroud)

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

  • 有一个默认的构造函数
  • 公开那些需要公开的属性

使用上面的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);

    }

}
Run Code Online (Sandbox Code Playgroud)

现在让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 
}
Run Code Online (Sandbox Code Playgroud)