如何返回json字符串 [英] How to return a json string

查看:130
本文介绍了如何返回json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我是WebAPI的新手,这是我第一次使用c#通过带有Entity Framework的visual studio创建一个。当我编译程序时,它不会给我一个错误。它让我下载结果,而不是在Internet Explorer中以json格式显示它。



如果我的英语不好或我无法清楚地解释我的问题,我很抱歉。我只是想看看Postman或Google Chrome中的输出。





Hi everyone,

I'm new to WebAPI, and this is my first time in creating one via visual studio with Entity Framework using c#. When i compile the program it doesn't give me an error. It let's me download the result instead of displaying it in json format in Internet Explorer.

I'm sorry if my english is bad or i can't explain my problem clearly. i just want to see the output in Postman or in Google Chrome.


<pre lang="c#"> using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebAPIDemo.Models;

namespace WebAPIDemo.Controllers
{
    public class EmployeeController : ApiController
    {
        private TestWebAPIEntities db = new TestWebAPIEntities();
        // GET api/CRUD  
        [ResponseType(typeof(IEnumerable<Employee>))]
        [Route("api/GetEmployees")]
        public IQueryable<Employee> GetEmployees()
        {
            return db.Employees;
        }

        //public IHttpActionResult GetEmployees()
        //{
        //    var companies = db.Employees.ToList();
        //    return Ok(new { results = companies });
        //}
        // GET api/CRUD/5  
        [ResponseType(typeof(Employee))]
        [Route("api/GetEmployee")]
        public IHttpActionResult GetEmployee(long id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }
            return Ok(employee);
        }
        // PUT api/CRUD/5  
        [Route("api/PutEmployee")]
        public IHttpActionResult PutEmployee(long id, Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != employee.ID)
            {
                return BadRequest();
            }
            db.Entry(employee).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return StatusCode(HttpStatusCode.NoContent);
        }
        // POST api/CRUD  
        [Route("api/PostEmployee")]
        [ResponseType(typeof(Employee))]
        public IHttpActionResult PostEmployee(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            db.Employees.Add(employee);
            db.SaveChanges();
            return CreatedAtRoute("DefaultApi", new
            {
                id = employee.ID
            }, employee);
        }
        // DELETE api/CRUD/5  
        [Route("api/DeleteEmployee")]
        [ResponseType(typeof(Employee))]
        public IHttpActionResult DeleteEmployee(long id)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return NotFound();
            }
            db.Employees.Remove(employee);
            db.SaveChanges();
            return Ok(employee);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        [Route("api/EmployeeExists")]
        private bool EmployeeExists(long id)
        {
            return db.Employees.Count(e => e.ID == id) > 0;
        } 
 }
} 





我尝试了什么:



我尝试更改



What I have tried:

I tried changing the code from

<pre>private TestWebAPIEntities db = new TestWebAPIEntities();
        // GET api/CRUD  
        [ResponseType(typeof(IEnumerable<Employee>))]
        [Route("api/GetEmployees")]
        public IQueryable<Employee> GetEmployees()
        {
            return db.Employees;
        }







to this:

//public IHttpActionResult GetEmployees()
        //{
        //    var companies = db.Employees.ToList();
        //    return Ok(new { results = companies });
        //}

推荐答案

[HttpGet]

[ProducesResponseType(typeof(Employee),200)]

[路线(api / GetEmployees)]

public IActionResult GetEmployees()

{



尝试

{

var data = db.Employees.ToList();

if(data == null)

返回NotFound(对不起,没有找到记录);

返回Ok(数据);



}

catch(例外情况)

{

返回NotFound(异常错误。记录未找到);

}

}
[HttpGet]
[ProducesResponseType(typeof(Employee), 200)]
[Route("api/GetEmployees")]
public IActionResult GetEmployees()
{

try
{
var data = db.Employees.ToList();
if (data == null)
return NotFound("Sorry, no records found");
return Ok(data);

}
catch (Exception exc)
{
return NotFound("Exception Error. Records Not Found");
}
}


public IEnumerable<Employee> GetEmployees()

{ 
   var companies = db.Employees.ToList();
     return Ok(companies);
}


这篇关于如何返回json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆