如何避免Web API中的JSON反序列化/序列化?

时间:2017-11-12 14:31:04

标签: asp.net-core .net-core

我在ASP.NET 2.0中的Web API控制器中有以下代码:

#include <stdio.h>
#include <stdlib.h>
#define bool int    
#define MAX(a,b) (((a)>(b))?(a):(b))

int upper_power_of_two(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;

}

int getMid(int s, int e)
{
  return s + (e -s)/2;  
}

void updateValueUtil(int segTree[], int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of 
// this segment
if (i < ss || i > se)
    return;

// If the input index is in range of this node, then update 
// the value of the node and its children
st[si] = st[si] + diff;
if (se != ss)
{
    int mid = getMid(ss, se);
    updateValueUtil(st, ss, mid, i, diff, 2*si + 1);
    updateValueUtil(st, mid+1, se, i, diff, 2*si + 2);
}
}

void updateValue(int arr[], int segTree[], int n, int i, int new_val)
{
// Get the difference between new value and old value
int diff = new_val - arr[i];

// Update the value in array
arr[i] = new_val;

// Update the values of nodes in segment tree
updateValueUtil(st, 0, n-1, i, diff, 0);
}

int rangeMinquery(int segTree[],int qlow,int qhigh,int low,int high,int pos)
{
if(qlow<=low && qhigh >=high)
    return segTree[pos];

if(qlow>high || qhigh <low)
        return 9999999999;
int mid=(low+high)/2;
return MAX(rangeMinquery(segTree,qlow,qhigh,low,mid,2*pos+1),rangeMinquery(segTree,qlow,qhigh,mid+1,high,2*pos+2));
}

int main()
{
int n,q,x,l,r,i;
scanf("%d %d %d %d",&n,&q,&l,&r);
int a[n];
int segTree[upper_power_of_two(n)];
printf("%d\n",upper_power_of_two(n));
while(q--)
{
    int cmd,pos1,pos2;
    scanf("%d %d %d",&cmd,&pos1,&pos2);
    if(cmd==1)
    {
        a[pos1]+=pos2;
        updateValue(a,segTree,n,1,0);
    }
    if(cmd==2)
    {
        x=rangeMinquery(segTree,pos1,pos2,0,n,0);
        printf("%d\n",x);
    }
}
return 0;
}    

如何在返回之前避免将responseJson反序列化为.NET对象,因为它已经是正确的JSON格式?

我尝试将方法更改为返回HttpResponseMessage,但这导致将错误的JSON传递回调用方。

2 个答案:

答案 0 :(得分:3)

ControllerBase类为此目的使用Content()方法。确保在输出包中设置正确的Content-Type标头:

return Content(responseJson, "application/json");

答案 1 :(得分:0)

您可以返回ContentResult而不是Ok()以避免不必要的序列化:

return new ContentResult
    {
        Content = responseJson,
        ContentType = "application/json",
        StatusCode = 200
    };