2017-04-19 2 views
0

내 HTML 클라이언트에서 API를 호출하려고합니다. 그것은 내게 내부 서버 오류를 제공하지만 나는 우편 배달부와 그것을 시도하면 작동합니다. 여기 웹 API 내부 서버 오류

는 API에 대한 내 코드입니다

[AcceptVerbs("POST")] 
    public dynamic Add(string post,string title, string user) 
    { 
     if (post == null) 
      throw new Exception("Post content not added"); 

     if (title == null) 
      throw new Exception("Post title not added"); 

     var u = UserManager.FindByEmailAsync(user); 
     Blog blog = Blog.Create(u.Result.Account.RowKey, post, title).Save(); 

     return new 
     { 
      id = blog.Id 
     }; 
    } 

내 html로 클라이언트가이

var d = { 
     post: post, 
     title: title, 
     user: user 
    } 

     $.ajax({ 
      type: 'POST', 
      url: apiUrl + 'Blog/Add', 
      contentType: "application/json; charset=utf-8", 
      dataType: 'json', 
      data: JSON.stringify(d) 
     }).done(function (data) { 

      console.log(data); 

     }).fail(function (error) { 

     }); 

처럼 여기 경로 API를 설정

 config.Routes.MapHttpRoute(
      name: "RPCApi", 
      routeTemplate: "{controller}/{action}/{id}", 
      defaults: new 
      { 
       id = RouteParameter.Optional 
      }, 
      constraints: new 
      { 
       subdomain = new SubdomainRouteConstraint("api") 
      } 
     ); 

수있는 사람의 도움을 내 코드입니다 저와 왜 html 클라이언트가 아닌 우편 배달부와 협력하고 있는지 설명해주십시오.

+0

어떤 오류가 발생합니까? – Yoav

+0

찾을 수 없습니다. 404. 기본적으로 API 끝점에 도달 할 수 없습니다. – mohsinali1317

+0

은 예외를 발생시키지 않습니다. 결과는 500입니다.이 경우 400 개의 결과를 반환해야합니다. –

답변

1

같은 유형 Int32이다. 컨트롤러가 오브젝트를 가져 가지 않으면 3 개의 필드가 필요합니다. 요청 메시지를 사용하여 페이로드를 보낼 때 객체로 보내야하며 웹 API에는 요청 메시지를 직렬화 할 수없는 단일 모델이 있어야합니다. 다음을 변경하면 자바 스크립트가 그대로 유지됩니다. 이것은 그것을 수행 방법 및 Angular2 HTTP Post ASP.NET MVC Web API 의 이전 답변을 참조하시기 바랍니다 같은 목표를 달성하기 위해 다른 방법으로 작동하는 이유에 대한 자세한 내용은

(제목의 클라이언트 프레임 워크를 무시하고는, 대답은 웹 API 2에 따라 다릅니다)

모델

public class SomethingToPost{ 
    [Required] 
    public string Post{get;set;} 
    [Required] 
    public string Title{get;set;} 
    public string User{get;set;} 
} 

제어기

[AcceptVerbs("POST")] 
public dynamic Add(SomethingToPost postThing) 
{ 
    // validation on ModelState 
    // action code 
} 
0

반환 유형이 dynamic 일 수 있습니다. 당신의 id 고려 int에 변경이

당신의 JSON 3 개 특성을 가진 개체를 나타 내기 때문에 그것은이다
[AcceptVerbs("POST")] 
public int Add(string post,string title, string user) 
{ 
    if (post == null) 
     throw new Exception("Post content not added"); 

    if (title == null) 
     throw new Exception("Post title not added"); 

    var u = UserManager.FindByEmailAsync(user); 
    Blog blog = Blog.Create(u.Result.Account.RowKey, post, title).Save(); 

    return blog.Id; 
} 
+0

아니요, 문제가 해결되지 않았습니다. 것은 우편 배달부에서 일하고있다. 그래서 내 클라이언트 측 코드에 문제가 있다고 가정합니다. – mohsinali1317