从零开始学习ASP.NET CORE(十一)Control入门

在控制器中加入两种方法,一种输出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的服务
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值