我在.net 4.5中开发了一个web api。当我测试api调用时,我收到500错误。只有在我发送XML时才会发生此行为。如果我使用表单URL编码字符串的JSON,服务器将正确处理请求。
我添加了
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
到WebApiConfig.cs并返回错误:
<Error><Message>An error has occurred.</Message><ExceptionMessage>Object reference not set to an instance of an object.</ExceptionMessage><ExceptionType>System.NullReferenceException</ExceptionType><StackTrace> at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()</StackTrace></Error>
我的标题是:
User-Agent: Fiddler
Content-Type: application/xml; charset=utf-8
Host: corebeta.pexcard.com
Content-Length: 119
我的要求是:
<Admin.CardListRequest>
<username>TestUser</username>
<password>GoodPassword</password>
</Admin.CardListRequest>
我的班级看起来像这样:
public class CardListRequest{
public string UserName { get; set; }
public string Password { get; set; }
}
WebAPI代码如下所示(日志使用的是log4net,没有任何内容写入该日志):
/// <summary>
/// Gets the list of open cardholders
/// </summary>
/// <param name="UserName">The username you use to log on to pexcardadmin.com</param>
/// <param name="Password">The password you use to log on to pexcardadmin.com</param>
/// <returns>A list of cardholders with balances</returns>
[HttpGet]
public List<Admin.Account> CardList(string UserName, string Password)
{
try
{
log.Info(String.Format("Admin Parameters: <UserName={0}>", UserName));
AuthenticateApi(UserName, Password, "cardList");
var Ret = GetCoreCardCardList(UserName, Password);
APIData.Response = "Success";
return Ret;
}
catch (Exception e)
{
log.Error(e);
APIData.Response = e.Message;
throw e;
}
finally
{
APIData.ResponseTime = DateTime.Now;
APILog.LogAPI(APIData);
}
}
/// <summary>
/// Gets the list of open cardholders
/// </summary>
/// <param name="Req"> The Request Parameter</param>
/// <returns>A list of cardholders with balances</returns>
[HttpPost]
public List<Admin.Account> CardList(Admin.CardListRequest Req)
{
APIData.ParamBlob = JsonConvert.SerializeObject(Req);
return CardList(Req.UserName, Req.Password);
}
有没有人对为什么会抛出此错误有任何想法?
谢谢, 史蒂芬
答案 0 :(得分:0)
通过确保XML正确来解决这个问题。为此,我创建了一个新的web api函数,它具有我想要的返回类型和我想填写的字段,并使用该确切的响应发送到web api。