Asp.net mvc 4 Web APi MVC4中的内部服务器错误500
我将一个HttpPost方法从控制器调用到Web API。对于其他方法,响应正常,并且该方法工作良好,除了下面提到的说明错误的方法Asp.net mvc 4 Web APi MVC4中的内部服务器错误500,asp.net-mvc-4,asp.net-web-api,Asp.net Mvc 4,Asp.net Web Api,我将一个HttpPost方法从控制器调用到Web API。对于其他方法,响应正常,并且该方法工作良好,除了下面提到的说明错误的方法 {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache Connection: Close Cache-Control: no-cac
{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; }
}
有什么建议吗
编辑1:
</Message><ExceptionMessage>No MediaTypeFormatter is available to read an object of type 'CustomerRequestResponse' from content with media type 'text/plain'.</ExceptionMessage>
没有MediaTypeFormatter可用于从媒体类型为“text/plain”的内容中读取“CustomerRequestResponse”类型的对象。
我要做的第一件事是验证客户端正在执行的请求是否正确-正确的url、标题和正文。为此,您可以在应用程序中启用fiddler
作为代理。将此部分添加到Web.config
中,然后在fiddler打开的情况下再次尝试运行代码-现在您应该能够在fiddler中看到请求:
<system.net>
<defaultProxy>
<proxy proxyaddress="http://127.0.0.1:8888" />
</defaultProxy>
</system.net>
如果请求正常,请检查您尝试连接到的服务器是否已实际启动并正在运行,以及它是否使用正确的头为您提供了正确的响应
我怀疑这足以确定问题所在
顺便说一句:在现实生活中,你的
catch
块实际上做了一些有用的事情吗?为了使它比现在更有用,您可以添加一些log4net日志记录,这可能也有助于识别未来的任何问题。我认为在处理MyAccountController的CustomerRegistration操作的数据时存在错误。我希望您检查控制器在执行过程中是否出现错误。如果您有标准DLL(后端)和Web脚本(前端:如ashx或aspx等)设置,则很容易忘记上载(到服务器)对Web脚本所做的更改。
我收到了这样一个错误,但是当我确保所有代码/脚本都同步并上传到服务器时,它就消失了。在调试中运行API控制器。它应该正好停在故障线路上。或者在这个方法的顶部设置一个断点并逐步执行,直到出现错误…抱歉--我错过了代码中的一个关键点--当我想调试这样的设置时,我运行了两个单独的VS实例--一个是客户端代码,另一个是api代码。这使得捕获服务器端错误非常容易。您可能还想考虑用调用堆栈将未处理的ExcEd日志记录到事件日志中。
<system.net>
<defaultProxy>
<proxy proxyaddress="http://127.0.0.1:8888" />
</defaultProxy>
</system.net>