且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C#方法返回一个JSON对象

更新时间:2023-02-14 17:32:52

RESP 已经是一个JSON字符串,但它不是有效的JSON(该键不裹引号(),如果返回到角,JavaScript的JSON.parse()来法无法反序列化,但您可以在反序列化使用JSON.NET它到JObject并再次序列化到有效的JSON并创建自己的的Htt presponseMessage ...

 公开的Htt presponseMessage的get()
{
    字符串userid = UrlUtil.getParam(这一点,用户ID,);
    字符串PWD = UrlUtil.getParam(这一点,PWD,);    字符串RESP = DynAggrClientAPI.openSession(用户ID,PWD);
    VAR jObject = JObject.Parse(RESP);    VAR响应= Request.CreateResponse(的HTTPStatus code.OK);
    response.Content =新的StringContent(jObject.ToString(),Encoding.UTF8,应用/ JSON);
    返回响应;
}

或者你也可以只返回 JObject 并启用网络API序列为你...

 公共JObject获得()
{
    字符串userid = UrlUtil.getParam(这一点,用户ID,);
    字符串PWD = UrlUtil.getParam(这一点,PWD,);    字符串RESP = DynAggrClientAPI.openSession(用户ID,PWD);
    VAR jObject = JObject.Parse(RESP);    返回jObject;
}

在任一情况下,在Web API调用应该返回此JSON,这是目前有效...

  {
  状态:成功
  数据:
    4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d
  ]
}

在角code,你必须挖掘出存储在名为数据数组中的会话ID ...

  userService.openUserSession(rzEnvJson)。然后(功能(响应){
    VAR sessionResponse = response.data; //或简单地响应,这取决于如果这是从$返回的HTTP承诺
    $ rootScope.rgSessionVars.sessionID = sessionResponse.data [0];
});

I am trying to fix an ASP.NET WebAPI method where a Json response is required. However it's returning a string instead.

Initially it was returing XML format, but I've added this line to the mvc code in App_Start\WebApiConfig.cs in order to return Json by default.

config.Formatters.Remove(config.Formatters.XmlFormatter);

We've updated the c# method as follows to use NewtonSoft:

public string Get()
{
    string userid = UrlUtil.getParam(this, "userid", "");
    string pwd = UrlUtil.getParam(this, "pwd", "");
    string resp = DynAggrClientAPI.openSession(userid, pwd);

    JsonSerializer ser = new JsonSerializer();
    string jsonresp = JsonConvert.SerializeObject(resp);

    return resp;
}

The resp var is coming back as a string type:

"{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}"

and jsonresp var looks like this :

"\"{status:\\\"SUCCESS\\\",data:[\\\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\\\"]}\""

and in Chrome's F12 dev tools, the data object is :

""{status:\"SUCCESS\",data:[\"4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d\"]}""

and in Console tools, the result of angular.fromJson(data) :

"{status:"SUCCESS",data:["4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d"]}"

I would appreciate some advice on how to properly return the Json object, and NOT in any string type.

thank you.

Bob

------------ UPDATE ----------------

By intercepting the resp var, and using Mr. Chu's suggestion below, I can successfully achieve a nice clean Json object on the client. The key is that resp needs to contains double quotes around both key:value pairs:

public HttpResponseMessage Get()
{
    string userid = UrlUtil.getParam(this, "userid", "");
    string pwd = UrlUtil.getParam(this, "pwd", "");
    string resp = DynAggrClientAPI.openSession(userid, pwd);

    resp = "{\"status\":\"SUCCESS\",\"data\":[\"194f66366a6dee8738428bf1d730691a9babb77920ec9dfa06cf\"]}";  // TEST !!!!!           

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(resp, System.Text.Encoding.UTF8, "application/json");
    return response;
}

in Chrome console, the response is :

Object {status: "SUCCESS", data: Array[1]}
data: Array[1]
status: "SUCCESS"
__proto__: Object

resp is already a JSON string, but it is not valid JSON (the keys are not wrapped in quotes ("). If it is returned to angular, the JavaScript JSON.parse() method is unable to deserialize it. However, you can use JSON.NET in deserialize it to a JObject and serialize it again into valid JSON and create your own HttpResponseMessage...

public HttpResponseMessage Get()
{
    string userid = UrlUtil.getParam(this, "userid", "");
    string pwd    = UrlUtil.getParam(this, "pwd", "" );

    string resp = DynAggrClientAPI.openSession(userid, pwd);
    var jObject = JObject.Parse(resp);

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(jObject.ToString(), Encoding.UTF8, "application/json");
    return response;
}

Or you can just return the JObject and have Web API serialize it for you...

public JObject Get()
{
    string userid = UrlUtil.getParam(this, "userid", "");
    string pwd    = UrlUtil.getParam(this, "pwd", "" );

    string resp = DynAggrClientAPI.openSession(userid, pwd);
    var jObject = JObject.Parse(resp);

    return jObject;
}

In either case, the Web API call should return this JSON, which is now valid...

{
  "status": "SUCCESS",
  "data": [
    "4eb97d2c6729df98206cf214874ac1757649839fe4e24c51d21d"
  ]
}

In the angular code, you'd have to dig out the session id which is stored in an array called data...

userService.openUserSession(rzEnvJson).then(function (response) {
    var sessionResponse = response.data; // or simply response, depending if this is a promise returned from $http
    $rootScope.rgSessionVars.sessionID = sessionResponse.data[0];
});