C# API仿IIS返回本地网页给浏览器显示

    近期用WINFORM写了一个无宿主API,现在客户要加一个设备说明书 htm格式,可通过接口访问; 如果是在IIS下此功能轻松实现,但在无宿主下只能单独写了; 直接上代码. 访问 接口方法为 https://127.0.0.1:8080/api/upload/sms/demo.htm   注:demo.htm 要先放在debug目录下

 public class uploadController : ApiController
    {
      
        /// <summary>
        // </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[Route("sms"), System.Web.Http.HttpGet]
        [HttpGet]
        public HttpResponseMessage sms()
        {
            try
            { 
                //Request.CreateResponse
                var requestUrl = Request.RequestUri;
                var fileName = System.IO.Path.GetFileName((requestUrl.LocalPath));
                string extension = Path.GetExtension(requestUrl.LocalPath);//扩展名 ".aspx"
                if (extension != ".html" && extension != ".htm" && extension != ".xls" && extension != ".xlsx" && extension != ".xml" && extension != ".txt")
                    throw new Exception("禁止访问此类文件");
                var FilePath = System.IO.Directory.GetCurrentDirectory() + "\\" + fileName;
                var stream = new FileStream(FilePath, FileMode.Open);
                //HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
                //response.Content = new StringContent(File.ReadAllText(FilePath, Encoding.UTF8), System.Text.Encoding.UTF8, "text/plain"); //new StreamContent(stream);
                response.Content = new StreamContent(stream);
                //用file协议下载文件时加以下,否则为浏览器直接打开
                //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                //response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                //{
                //    FileName = fileName
                //};
                return response;
            }
            catch
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.NoContent);
            }
        }
    
    
    
    
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值