从json调用读取十进制时出错

时间:2014-12-15 18:13:13

标签: c# asp.net-mvc json asp.net-web-api

我有一个mvc项目,我尝试将 SortedDictionary 发布到web api,然后返回小数。

但是该方法返回错误

System.AggregateException was unhandled by user code
HResult=-2146233088
Message=Der opstod en eller flere fejl.
Source=mscorlib
StackTrace:
   ved System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   ved System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   ved System.Threading.Tasks.Task`1.get_Result()
   ved GUI.CalculationGateway.GetOrderSum(SortedDictionary`2 order) i c:\Users\MichaelTot\Desktop\Code Projects\Skole\SVN\trunk\GUI\GUI\Infrastructure\CalculationGateway.cs:linje 16
   ved GUI.Controllers.CartController.ShowCart() i c:\Users\MichaelTot\Desktop\Code Projects\Skole\SVN\trunk\GUI\GUI\Controllers\CartController.cs:linje 49
   ved lambda_method(Closure , ControllerBase , Object[] )
   ved System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   ved System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   ved System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   ved System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
   ved System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   ved System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   ved System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   ved System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   ved System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   ved System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
   ved System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
InnerException: Newtonsoft.Json.JsonReaderException
   HResult=-2146233088
   Message=Error reading decimal. Unexpected token: StartObject. Path '', line 1, position 1.
   Source=Newtonsoft.Json
   LineNumber=1
   LinePosition=1
   Path=""
   StackTrace:
        ved Newtonsoft.Json.JsonReader.ReadAsDecimalInternal()
        ved Newtonsoft.Json.JsonTextReader.ReadAsDecimal()
        ved Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
        ved Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
        ved Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
        ved Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
        ved System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        ved System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
     --- Afslutningen på staksporingen fra den tidligere placering, hvor undtagelsen blev udløst ---
        ved System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        ved System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        ved System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
        ved System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0`1.MoveNext()
   InnerException: 

据我所知,价值路径存在问题。但是,我不知道问题可能是什么,因为我对web api&json和json都很陌生。

我的代码看起来像这样

public class CalculationGateway
{
    public decimal GetOrderSum(SortedDictionary<WareDTO, int> order)
    {
        string path = "api/calculation/GetOrderSum";
        return GetClient().PostAsJsonAsync(path, order).Result.Content.ReadAsAsync<decimal>().Result;
    }

    protected HttpClient GetClient()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:26519");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json")
            );
        return client;
    }
}


public class CalculationController : ApiController
{
    CalculationRepository repository;

    public CalculationController()
    {
        repository = new Facade().GetCalculationRepository();
    }

    [Route("api/calculation/GetOrderSum/{order}")]
    public decimal GetOrderSum(SortedDictionary<WareDTO, int> order)
    {
        return repository.OrderSum(order);
    }
}


public class Facade
{
    private CalculationRepository calculationRepository;

    public CalculationRepository GetCalculationRepository()
    {
        return calculationRepository == null
            ? calculationRepository = new CalculationRepository()
            : calculationRepository;
    }
}


public class CalculationRepository
{
    public decimal OrderSum(SortedDictionary<WareDTO, int> order)
    {
        decimal result = 0;

        foreach (var e in order)
            result += calculator.MultiplyNumber(e.Key.price, e.Value);

        return result;
    }
}

0 个答案:

没有答案