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 ...
随机推荐
- Official Documents
1. Docker Installation https://docs.docker.com/install/linux/docker-ee/suse/ 2. Docker hub https://d ...
- [bzoj3209]花神的数论题_数位dp
花神的数论题 bzoj-3209 题目大意:sum(i)表示i的二进制表示中1的个数,求$\prod\limits_{i=1}^n sum(i)$ 注释:$1\le n\le 10^{15}$. 想法 ...
- hdu1203--D - I NEED A OFFER!(转化01背包)
D - I NEED A OFFER! Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u ...
- [Cypress] Find and Test Focused Input with Chrome’s DevTools in Cypress
In this lesson, we’ll add tests that finds a focused input. We’ll use Chrome’s dev tools from inside ...
- HDOJ GCD 2588【欧拉函数】
GCD Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- 略过天涯 深入浅出VGA和DVI接口【转】
本文转载自:http://www.cnblogs.com/lueguo/p/3373649.html 由CrazyBingo修改…… 前言:目前显示器的主流接口是VGA.DVI以及HDMI,再加上一个 ...
- LightOJ--1152--Hiding Gold(二分图奇偶建图)(好题)
Hiding Gold Time Limit: 2000MS Memory Limit: 32768KB 64bit IO Format: %lld & %llu Submit Sta ...
- oracle表类似:BIN$dJ5h8mA4Lr/gQAB/AQB0oA==$0 TABLE
今天看到数据库中有很多类似: TNAME TABTYPE CLUSTERID ------------------------------ ---- ...
- xss 记录cookie
<p> <img src="http://act.ci123.com/global/ueditor_new/php/upload/98591403834900.jpg&qu ...
- javascript必须知道的知识要点(一)
该文章不详细叙述各知识要点的具体内容,仅把要点列出来,供大家学习的时候参照,或者检测自己是否熟练掌握了javascript,清楚各个部分的内容. 语句 注释 输出 字面量 变量 数据类型 typeof ...