如何应对angularjs串primites和$ HTTP?如何应对、angularjs、HTTP、primites

2023-09-13 03:35:30 作者:情深意浓

在ASP.NET Web API函数返回JSON一个简单的字符串。

An ASP.NET Web Api function returns a simple string in JSON.

当我打电话从angularjs这个功能,我得到一个带引号的字符串,而不是一个简单的字符串:

When I call this function from angularjs, I get a quoted string, not a simple string:

return $http.post('/api/orders', data).then(function (results) {
        return result.data;

result.data是我的字符串,用引号。因为返回的消息是原始的字符串,而不是一个对象,是因为。如何是适当的方式来处理呢?使用js函数时去掉引号?强制服务器返回一个对象,而不是原始的?一些特殊的配置? ...?

result.data is "my string", with quotes. It is due because the returned message is a string primitive, not a object. How is the appropriate way to deal with it? Removing quotes using a js function? Forcing to server to return a object instead of primitive? some special configuration? ...?

更新:

服务器使用一个Web API控制器返回字符串:

The server uses a Web Api controller that returns a string:

 public IHttpActionResult SaveOrder() {return Ok("this is a test");}

它具有相同的结果是:

it has the same result that:

 public string  SaveOrder() {return "this is a test";}

的问题是,返回的JSON值不是一个对象,它直接字符串原始。

The problem is that the returned JSON value is not an object, it is directly the string primitive.

推荐答案

我有同样的问题。这是因为你正在返回字符串从您的控制器,我认为它看起来是这样的:

I had the same problem. It happens because you are returning string from your controller, I assume it looks something like this:

public string ControllerMethod(..) {...}

您应该返回的Htt presponseMessage 而不是字符串,而对象将是这样的:

You should be returning HttpResponseMessage instead of string, and the object will be like this:

public HttpResponseMessage ControllerMethod() 
{
    var myString = "my string";
    return new HttpResponseMessage()
    {
        Content = new StringContent(myString, Encoding.UTF8, "text/html")
    };
}