2017-04-19 161 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