我正在尝试将我的 winforms 应用程序中的对象列表发布到我的 asp.net mvc 4 网站。我已经测试过发布一个对象,它有效,但不适用于列表。它返回 500(内部服务器错误)
。这是我的代码:
ASP.NET MVC 网络 API
public class PostTraceController : ApiController
{
public HttpResponseMessage Post(List<WebTrace> list)
{
try
{
// Some code
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
HttpContext.Current.Trace.Write("exception", ex.Message);
return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex);
}
}
public HttpResponseMessage Post(WebTrace item)
{
try
{
// Some code
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
HttpContext.Current.Trace.Write("exception", ex.Message);
return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex);
}
}
}
Win 表单应用程序
public class BaseSender
{
public BaseSender()
{
Client = new HttpClient
{
BaseAddress = new Uri(@"http://localhost/mywebsite/")
};
Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public string UserCode { get; set; }
protected readonly HttpClient Client;
public HttpResponseMessage PostAsJsonAsync(string requestUri, object value)
{
var response = Client.PostAsJsonAsync(requestUri, value).Result;
response.EnsureSuccessStatusCode();
return response;
}
}
public class WebTraceSender : BaseSender
{
private const string requestUri = "api/posttrace";
public bool Post(List<ArchiveCptTrace> list)
{
try
{
var listWebTrace = new List<WebTrace>();
foreach (var item in list)
{
listWebTrace.Add(new WebTrace
{
DateStart = item.DatePreparation,
DateEnd = item.DateCloture,
UserStart = item.UserPreparation.UserName,
UserEnd = item.UserCloture.UserName,
AmountStart = item.MontantPreparation,
AmountEnd = item.MontantCloture,
TheoricAmountEnd = item.MontantTheorique,
Difference = item.Ecart,
UserCode = UserCode
});
}
var responce = PostAsJsonAsync(requestUri, listWebTrace);
return responce.IsSuccessStatusCode;
}
catch (Exception e)
{
// TODO : Trace the exception
return false;
}
}
}
编辑:
我发现了错误的场景,我的 api Controller 中有两个方法,甚至认为它们具有不同的签名。如果我评论一种方法,帖子工作正常(项目或列表)。有什么想法吗?
最佳答案
这些方法可能有不同的签名,但 Web API 无法在不检查主体的情况下区分它们之间的区别,出于性能原因,它不会这样做。
您可以做两件事 - 创建一个仅包含 WebTrace 对象列表的新类,并将其放入不同的 API Controller 中,或者您可以将自定义路由映射到现有方法之一。您可以使用 ActionName
属性来做到这一点,但是,我可能会采用第一种方法。
关于asp.net-mvc - ASP.NET MVC Web API : Posting a list of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207017/