在控制器中加入两种方法,一种输出object格式,一种输出json格式,代码如下
public class HomeController : Controller
{
private readonly IStudentRepository studentRepository;
public HomeController(IStudentRepository _studentRepository)
{
studentRepository = _studentRepository;
}
public string Index(int id)
{
return studentRepository.GetStudent(id).Name;
}
public ObjectResult DetailObjct()
{
Student student = studentRepository.GetStudent(1);
return new ObjectResult(student);
}
public JsonResult DetailJson()
{
Student student = studentRepository.GetStudent(2);
return Json(student);
}
}
运行结果
这里我们可以看到,json格式没有正常显示,我们可以用到工具fiddler或者postman,输入我们请求的url,可以得到我们想看到的json格式
1、Fiddler:
2、Postman:
在启动类startup里面的mvc服务后面加入一个方法,可以获得xml文件格式
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(option => option.EnableEndpointRouting = false).AddXmlDataContractSerializerFormatters();
services.AddSingleton<IStudentRepository, StudentRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
......
}
}
在请求头里我们需要加入Accept: application/xml,得到xml的文件结果
1、Fiddler:
2、postman:
总结:
- control里面可以返回不同的格式,只要通过在方法的返回值中进行处理
- xml类型需要在启动类中额外添加一下xml的服务