使用 XML 调用 Web API 时出现 500 错误
本文关键字:错误 API XML 调用 Web 使用 | 更新日期: 2023-09-27 17:56:28
我在.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 代码如下所示(log 正在使用 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);
}
有没有人对为什么抛出此错误有任何想法?
谢谢史蒂文
此问题已通过确保 XML 正确得到解决。 为此,我创建了一个新的 Web api 函数,该函数具有我想要的返回类型并填写了我想要的字段,并使用该确切的响应发送到 Web api。