如何在ASP.NET Core Razor页面项目中将文本或二进制数据传递到浏览器

时间:2019-02-09 10:46:43

标签: asp.net razor asp.net-core

使用下面的代码,我希望仅在用户的浏览器中显示字符串abcdefg。相反,用户访问此页面时会在浏览器中获取以下JSON:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["text/plain"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace MyProject.Pages
{
    [Route("api/Mvc")]
    public class MvcController : Controller
    {
        //public IActionResult Index()
        //{
        //    return View();
        //}

        public Task<HttpResponseMessage> Get(int imageid)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent("abcdefg");
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

            return Task.FromResult(response);

        }
    }
}

我是这个平台的新手,从根本上误解了一些东西,但是我的搜索无济于事。

此代码的最终目的是将mime类型更改为image/jpeg,并使用StreamContent来传递二进制数据(存储在数据库中的jpeg图像)。

1 个答案:

答案 0 :(得分:1)

找到了https://gist.github.com/divinity76/544d7cadd3e88e057ea3504cb8b3bf7e

对于文本:

    public ActionResult Get(int imageid)
    {
        return Content("abcdefg");
    }

对于二进制文件:

    public ActionResult Get(int imageid)
    {
        byte[] data = GetData(imageid);
        return File(data, "image/jpeg");
    }