2017-04-19 242 views
0

我想从我的HTML客户端调用api。它给了我内部的服务器错误,但是当我用邮递员尝试它的时候它就起作用了。Web 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

不要抛出'Exception' - 这将导致500.你应该返回400结果在这些情况下。 –

回答

1

这是因为你的JSON表示有3个属性的对象。你的控制器不需要一个对象,它需要3个字段。当使用请求消息发送一个有效载荷时,您必须将它作为一个对象发送,并且您的web api必须有一个可以将请求消息反序列化的单一模型。更改以下内容将起作用,您的JavaScript将保持不变。

更多关于为什么这个工作它的方式和其他方式来达到同样的目标,请参阅Angular2 HTTP Post ASP.NET MVC Web API 以前的答案(忽略标题的客户端框架,答案是特定的Web 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。将其更改为int考虑您的idInt32型像

[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