linux部署.net core api并且实现上传图片
为了体验.net在linux上运行,所以使用HttpClient东借西抄做了一个简单的api上传功能。
第一步,简单的上传功能:
public class UploadHelper
{
private static readonly string controller = "/api/Upload";
/// <summary>
/// 使用HttpClient上传附件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static async Task<string> Upload(string filePath)
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
HttpContent httpContent = new StreamContent(fileStream);
httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
string filename = filePath.Substring(filePath.LastIndexOf("\\") + );
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add("user-agent", "User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");
using (MultipartFormDataContent mulContent = new MultipartFormDataContent("----WebKitFormBoundaryrXRBKlhEeCbfHIY"))
{
mulContent.Add(httpContent, "file", filename);
string ip = ConfigurationProvider.configuration.GetSection("webapi:HttpAddresss").Value;
string url = "http://"+ip + controller;
return await HttpHelper.PostHttpClient(url, nameValueCollection, mulContent);
} }
}
public class HttpHelper
{
/// <summary>
/// httpclient post请求
/// </summary>
/// <param name="url"></param>
/// <param name="RequestHeaders"></param>
/// <param name="multipartFormDataContent"></param>
/// <returns></returns>
public static async Task<string> PostHttpClient(string url, NameValueCollection RequestHeaders,
MultipartFormDataContent multipartFormDataContent)
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (HttpClient client = new HttpClient(handler))
{
client.MaxResponseContentBufferSize = ;
client.DefaultRequestHeaders.Add(RequestHeaders.Keys[],RequestHeaders[RequestHeaders.Keys[]]);
HttpResponseMessage httpResponseMessage = await client.PostAsync(url, multipartFormDataContent);
httpResponseMessage.EnsureSuccessStatusCode();
string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
return result;
}
}
}
然后自己再写一个api程序做为服务端用来接收请求,如下代码:
[Route("api/[controller]")]
[ApiController]
public class UploadController : ControllerBase
{
private IHostingEnvironment hostingEnvironment;
public UploadController(IHostingEnvironment _hostingEnvironment)
{
hostingEnvironment = _hostingEnvironment;
}
[HttpPost]
public IActionResult Upload()
{
try
{
var imgFile = Request.Form.Files[];
int index = imgFile.FileName.LastIndexOf('.');
//获取后缀名
string extension = imgFile.FileName.Substring(index, imgFile.FileName.Length - index);
string webpath = hostingEnvironment.ContentRootPath;
string guid = Guid.NewGuid().ToString().Replace("-", "");
string newFileName = guid + extension;
DateTime dateTime = DateTime.Now;
//linux环境目录为/{1}/
string path = string.Format(@"{0}/TemporaryFile/{1}/{2}/{3}", "/home/www", dateTime.Year.ToString(), dateTime.Month.ToString()
, dateTime.Day.ToString());
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string imgSrc = path + @"/" + newFileName;
using (FileStream fs = System.IO.File.Create(imgSrc))
{
imgFile.CopyTo(fs);
fs.Flush();
}
return new JsonResult(new { message = "OK", code = });
}
catch (Exception e)
{
return new JsonResult(new {message=e.Message,code=});
}
}
api程序记得修改Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
//本地启动
//public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
// WebHost.CreateDefaultBuilder(args).UseUrls("http://*:5000")
// .UseStartup<Startup>();
//linux启动
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
当时我访问出现502就是因为这个原因
然后本地测试可以之后再将api部署到linux服务器,部署linux需要一下工具:
XFTP:将发布好的api程序传到linux,
Ngnix:反向代理,参考菜鸟教程https://www.runoob.com/linux/nginx-install-setup.html,我的配置是这个,记得将5000加入防火墙,并且网络策略这个端口:
user www www;
worker_processes ; #设置值和CPU核心数一致
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志级别
pid /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile ;
events
{
use epoll;
worker_connections ;
}
http
{ #下面是server虚拟主机的配置
server {
listen ;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
} }
具体的部署过程网上很多教程。部署好之后就可以试着用postman或浏览器输入地址访问了。
因为linux的机制当你退出linux后就无法访问,所以需要配置进程守护,我的配置如下
[program:BlogApi]
command=dotnet BlogApi.dll
directory=/home/wwwroot/BlogAPI/
stderr_logfile=/var/log/BlogApi.error.log
stdout_logfile=/var/log/BlogApi.stdout.log
environment=ASPNETCORE_ENVIRONMENT=Production
user=root
stopsignal=INT
autostart=true
autorestart=true
startsecs=
更新重启守护进程,然后你就可以随时随地访问了,
打个广告:游戏也能赚钱?如果你热爱游戏,并且想通过游戏赢得零花钱,5173是个不错的选择 http://www.5173.com/?recommenduserid=US15061749098191-04F6
linux部署.net core api并且实现上传图片的更多相关文章
- 部署.Net Core APi+Vue 到 linux centos 服务器(一)
部署.Net Core APi+Vue 到 linux centos 服务器(一) 前言:项目采用的是 .net core 作为接口,vue作为前端. 此时需要把整个项目架设到linux centos ...
- 国产中标麒麟Linux部署dotnet core 环境并运行项目 (三) 部署运行WEB API项目
部署dotnet Core Web API 上一步的文章,是我们公司最核心的一个ORM组件,在中标麒麟系统完成了一个插入数据的任务,这一步是将正式的从dot net framework 迁移到 dot ...
- Linux 部署.Net Core 项目
前面也有说到,我学习Linux 主要因为要学习一下部署.NET CORE项目到Linux 系统,这里就记录一下部署的详细步骤吧. 主要需要安装以下几个工具 1..NET CORE SDK 2.Jexu ...
- 国产中标麒麟Linux部署dotnet core 环境并运行项目 (一) 安装dotnet core
背景 根据我之前写的文章 将 Net 项目升级 Core项目经验:(一)迁移Net项目为Net Core\Standard项目,我们将公司内部最核心的ORM框架迁移到net core 上面,并在win ...
- linux部署.net Core项目
首篇笔记,多多关照.方便回忆和给新手指导,大神绕道 首先在Linux系统部署.net Core项目首先准备一个Linux系统的服务器,百度云,阿里云都行. 1.net core 部署在Linux系统上 ...
- 国产中标麒麟Linux部署dotnet core 环境并运行项目 (二) 部署运行控制台项目
背景 在上一篇文章安装dotnet core,已经安装好dotnet core了.之前只是安装成功了dotnet, 输入dotnet --info,可以确认安装成功了,但是在运行代码时,还是报错了,本 ...
- CentOS+Linux部署.NET Core应用程序
工具: WinSCP+Xshell+VMware 1.安装CentOS 省略安装过程... 2. 安装.Net Core Sdk ①更新可用的安装包:sudo yum update ②安装.NET需要 ...
- linux 部署 .net core mvc
1.本地编写一个mvc网站 代码编辑器:Visual studio 2017.2019.Visual Code 均可 1)搭建 略. (请自行搜索如何编辑mvc,或看文末参考链接) 2)配置 Prog ...
- linux 部署.net core 环境
Linux版本Ubuntu 16.04 .net core 下载地址:https://dotnet.microsoft.com/download/dotnet-core/2.1 虽然现在现在.net ...
随机推荐
- Spring深入理解(三)
Spring 中 AOP 特性详解 动态代理的实现原理 要了解 Spring 的 AOP 就必须先了解动态代理的原理,因为 AOP 就是基于动态代理实现的.动态代理还要从 JDK 本身说起. 在 Jd ...
- Codeforces 525E Anya and Cubes 中途相遇法
题目链接:点击打开链接 题意: 给定n个数.k个感叹号,常数S 以下给出这n个数. 目标: 随意给当中一些数变成阶乘.至多变k个. 再随意取一些数,使得这些数和恰好为S 问有多少方法. 思路: 三进制 ...
- HDU 4530
今天让人看不起了,话说好伤心,说我搞了ACM那么久都没获得拿得出手的奖.... 今晚爷爷我要狂刷2013腾讯马拉松的水题,奶奶滴,哈哈哈哈...T_T #include <iostream> ...
- Heat-AutoScaling
在openstack的I版本号中,Heat中加入了对于AutoScaling资源的支持,github上也提供了相应的AutoScaling的模板,同一时候也支持使用ceilometer的alarm来触 ...
- Scala入门到精通——第一节 Scala语言初步
本节主要内容 Scala简单介绍 为什么要学习Scala Scala语言初步 1. Scala简单介绍 Scala(Scala Language的简称)语言是一种能够执行于JVM和.Net平台之上的通 ...
- fastjson null 值处理
偶然用到fastjson转换json 在前台用js解析竟然某些字段没有,曾经用过gson.联想到是不是相似gson默认将null值不显示了,找了下资料果真如此 直接上代码吧 import java.u ...
- HDUOJ 水果
/*水果 夏天来了~~好开心啊,呵呵,好多好多水果~~ Joe经营着一个不大的水果店.他觉得生存之道就是经营最受顾客欢迎的水果. 如今他想要一份水果销售情况的明细表,这样Joe就能够非常easy ...
- Android 四大组件学习之ContentProvider二
上节学习了什么是ContentProvider.以及ContentProvider的作用.以及什么是URL.本节就对上节学习的知识做一个实践,也就是定义自己的ContentProvider 好.实践是 ...
- android app 架构设计01
1:本文有摘抄, 1 2 3 4 5 - 开发过程中.需求.设计.编码的一致性 - 整个程序具有统一的风格,比方对话框样式,button风格,色调等UI元素 - 整个程序详细统一的结构,比方不同模块訪 ...
- luogu1965 转圈游戏
题目大意 n 个小伙伴(编号从 0 到 n-1)围坐一圈玩游戏.按照顺时针方向给 n 个位置编号,从0 到 n-1.最初,第 0 号小伙伴在第 0 号位置,第 1 号小伙伴在第 1 号位置,--,依此 ...