2013-08-16 90 views
-2

我从控制器调用Web API的HttpPost方法。对于其他方法,响应是OK和方法效果很好,除了下面提到的方法,指出错误Web API中的内部服务器错误500 MVC4

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Pragma: no-cache 
    Connection: Close 
    Cache-Control: no-cache 
    Date: Fri, 16 Aug 2013 09:49:25 GMT 
    Server: ASP.NET 
    Server: Development 
    Server: Server/10.0.0.0 
    X-AspNet-Version: 4.0.30319 
    Content-Length: 1855 
    Content-Type: application/json; charset=utf-8 
    Expires: -1 
}} 

我的方法

public int CustomerRegistration(CustomerRequestResponse req) 
     { 
       try 
       { 
        HttpClient client = new HttpClient(); 
        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ServerAddress"].ToString()); 
        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json")); 
        Uri gizmoUri = null; 
        var Response = client.PostAsJsonAsync("api/MyAccount/CustomerRegistration", req).Result; 
        int result = 0; 
        if (Response.IsSuccessStatusCode) 
        { 
         gizmoUri = Response.Headers.Location; 
         result = Response.Content.ReadAsAsync<Int32>().Result; 
        } 
        return result; 
       } 
       catch { throw; } 
      } 

我怎么能确定哪里是我的代码中的错误。有什么建议么 ??

编辑:: 追述异常确定 “System.Net.Http.ObjectContent”

{Method: POST, RequestUri: 'http://localhost:56003/api/MyAccount/CustomerRegistration', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[ServiceEntities.MyAccount.CustomerRequestResponse, ServiceEntities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Headers: 
{ 
    Accept: application/json 
    Content-Type: application/json; charset=utf-8 
    Content-Length: 495 
}} 

任何建议修复它?

EDIT1:

</Message><ExceptionMessage>No MediaTypeFormatter is available to read an object of type 'CustomerRequestResponse' from content with media type 'text/plain'.</ExceptionMessage> 
+1

在DEBUG中运行你的API控制器。它应该停在失败的路线上。或者在此方法的顶部设置一个断点并逐步进行,直到出现错误。 –

+1

...对不起 - 我错过了代码中的一个关键点 - 当我想要调试像这样的设置时,我运行两个独立的VS实例 - 一个带有客户端代码,另一个带有API代码。这使得捕获服务器端错误非常容易。您可能还想考虑使用调用堆栈将未处理的exeptions记录到事件日志或无论如何。 –

+0

使用try和catch并记录错误 –

回答

2

我会做的第一件事是验证客户端是做请求是正确的 - 正确的网址,标题,正文。为此,您可以在应用程序中启用fiddler作为代理。本栏目添加到您Web.config,并尝试与小提琴手再次打开运行代码 - 现在你应该可以看到提琴手请求:

<system.net> 
    <defaultProxy> 
    <proxy proxyaddress="http://127.0.0.1:8888" />  
    </defaultProxy> 
</system.net> 

如果请求是好的,检查服务器你要连接它实际上已经启动并正在运行,并且它以正确的标题为您提供了正确的响应。

我怀疑它应该足以确定问题。

顺便说一句:在现实生活中,你的catch块实际上有用吗?为了使它比现在更有用,你可以添加一些log4net日志记录,这可能也有助于识别未来的问题。

0

我认为在处理MyAccountController的CustomerRegistration操作数据时存在一个错误。如果在进行过程中发生错误,我宁愿您检查您的控制器。

0

如果您有标准DLL(后端)和Web脚本(前端:如ashx或aspx等)设置,那么很容易忘记上传(到服务器)对Web脚本所做的更改。 我收到了这样的错误,但是当我确认我的所有代码/脚本都处于同步状态并上传到服务器时,它就消失了。