POST JSON with MVC 4 API Controller
내가 가지고 있는 코드는 다음과.
   $.ajax({
        type: "POST",
        url: "/api/slide",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: '{"Title":"fghfdhgfdgfd"}',
        dataType: "json",
 
이것은 내 관제사입니다.
public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post(string Title)
    {
    }
 
코드를 실행하고 /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
뷰 모델을 정의합니다.
public class SlideViewModel
{
    public string Title { get; set; }
}
 
그런 다음 컨트롤러 작업에서 이 뷰 모델을 인수로 받아들이도록 합니다.
public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post(SlideViewModel model)
    {
        ...
    }
}
 
마지막으로 작업을 호출합니다.
$.ajax({
    type: 'POST',
    url: '/api/slide',
    cache: false,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ title: "fghfdhgfdgfd" }),
    success: function() {
        ...    
    }
});
 
그 이유는 문자열과 같은 단순한 형태는 URI로부터 바인딩되기 때문입니다. 또한 Web API에서 모델 바인딩에 대한 아래 기사를 읽어보시기 바랍니다.
변환하려는 개체에 기본(빈) 생성자가 있는지 확인합니다.
경험칙:개체로 병렬화하려면 개체를 쉽게 만들 수 있어야 합니다.이 지침은 다음과 같은 도움을 줄 수 있습니다.
전달할 모든 속성은 공용이어야 합니다.
매개 변수 없이 객체를 구성할 수 있어야 합니다.
JSON 문자열/객체는 다음과 같습니다.
{ Name: "John Doe", Phone: "123-456-7890", Pets: [ "dog", "cat", "snake" ] }
 
다음 클래스에서 개체로 변환할 수 있습니다.
 public class Person {
     public string Name { get; set; }
     public string Phone { get; set; }
     public string[] Pets { get; set; }
  }
 
또는 이것:
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;
   }
}
 
또는 이것:
public class Person {
    public string Name { get; set; }
    public string Phone { get; set; }
    public string[] Pets { get; set; }
    public Person() {}
 }
 
하지만 이건 아닙니다.
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;
    }
}
 
이제 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 
}
 
클래스에 기본 생성자가 없거나 클래스의 소스 코드에 액세스할 수 없는 경우 다음과 같은 어댑터 클래스를 만들 수 있습니다.
- 기본 생성자가 있습니다.
 - 공개해야 할 재산을 공개합니다.
 
기본 생성자가 없는 위의 사용자 클래스를 사용하면 어댑터가 다음과 같이 보일 수 있습니다.
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);
    }
}
 
이제 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 
}
시도해 보기:
$.ajax({
    type: "POST",
    url: "/api/slide",
    data: { Title: "fghfdhgfdgfd" }
});
 
이는 데이터 속성을 둘러싼 인용문이 원인입니다.
즉, >> 데이터: { 제목: "fghfdhgfdgfd" }
not >> 데이터: '{ 제목: "fghfdhgfdgfd" }'
업데이트:
또한 당신의 컨트롤러는 조금 이상해 보이지만 당신의 라우팅 등을 보지 않고는 구분하기 어렵습니다.
저는 이와 같은 것을 볼 수 있기를 기대합니다.
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;
    }
}
 
분명히, 당신도 당신의 jQuery에서 URL을 업데이트해야 합니다.
여기를 보십시오.
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
또 다른 업데이트:
당신의 Json과 일치하는 CLR 객체를 만들고 그것에 직접 바인딩하기 위해 MVC 모델 바인더를 사용하는 것이 일반적일 것입니다.이 작업을 원하지 않는 경우 개체에 바인딩하고 사전으로 역직렬화할 수 있습니다.
// POST api/values
public void Post(object json)
{
    Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json.ToString());
    var x = values["Title"];
}
작업 매개 변수를 FromBody로 캐스팅합니다. 즉,
public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post([FromBody]string Title)
    {
    }
}
$.ajax({
    type: 'POST',
    url: '/api/slide',
    cache: false,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ title: "fghfdhgfdgfd" }),
    success: function() {
        ...    
    }
});
 
컨트롤러는
public class SlideController : ApiController
{
    // POST /api/Slide
    public void Post(string Title)
    {
    }
 
url이 올바르지 않습니다. url은 슬라이드 컨트롤러에 게시 작업을 처리해야 합니다.
: "url 로 합니다 을  합니다"로 url을 합니다.~/ControllerName/ActionName에서 "  에서  는 는     에서    Url:"~/Slide/Post"
언급URL : https://stackoverflow.com/questions/12446024/post-json-with-mvc-4-api-controller
'programing' 카테고리의 다른 글
| Oracle BLOB 필드에서 파일을 추출하려면 어떻게 해야 합니까? (0) | 2023.09.08 | 
|---|---|
| 아이폰에서 방향 변경 시 웹 앱의 스케일/줌을 재설정하려면 어떻게 해야 합니까? (0) | 2023.09.08 | 
| mysql db에서 중복 항목을 제거하는 방법은 무엇입니까? (0) | 2023.09.03 | 
| jquery는 자바스크립트 라이브러리입니까, 아니면 프레임워크입니까? (0) | 2023.09.03 | 
| scanf()를 사용하여 여러 값 가져오기 (0) | 2023.09.03 |