Return JsonResult from web api without its properties

前端 未结 4 2097
日久生厌
日久生厌 2021-01-31 10:34

I have a Web API controller and from there I\'m returning an object as JSON from an action.

I\'m doing that like this:

public ActionResult GetAllNotifica         


        
4条回答
  •  我在风中等你
    2021-01-31 10:57

    I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

    Here is how I solved it. First I declared a utility class

    public class RawJsonActionResult : IHttpActionResult
    {
        private readonly string _jsonString;
    
        public RawJsonActionResult(string jsonString)
        {
            _jsonString = jsonString;
        }
    
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var content = new StringContent(_jsonString);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
            return Task.FromResult(response);
        }
    }
    

    This class can then be used in your controller. Here is a simple example

    public IHttpActionResult Get()
    {
        var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
        return new RawJsonActionResult(jsonString);
    }
    

提交回复
热议问题