欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

linux部署.net core api并且实现上传图片

程序员文章站 2023-10-26 16:15:34
为了体验.net在linux上运行,所以使用HttpClient东借西抄做了一个简单的api上传功能。 第一步,简单的上传功能: 然后自己再写一个api程序做为服务端用来接收请求,如下代码: api程序记得修改Program.cs 当时我访问出现502就是因为这个原因 然后本地测试可以之后再将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("\\") + 2);
            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 = 256000;
                client.defaultrequestheaders.add(requestheaders.keys[0],requestheaders[requestheaders.keys[0]]);
                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[0];
                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 = 200 });
            }
            catch (exception e)
            {
                return new jsonresult(new {message=e.message,code=500});
            }
        }

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:反向代理,参考菜鸟教程,我的配置是这个,记得将5000加入防火墙,并且网络策略这个端口:

user www www;
worker_processes 2; #设置值和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 65535;
events
{
  use epoll;
  worker_connections 65535;
}
http
{
 
 #下面是server虚拟主机的配置
        server {
    listen 80;
    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=3

更新重启守护进程,然后你就可以随时随地访问了,

 

打个广告:游戏也能赚钱?如果你热爱游戏,并且想通过游戏赢得零花钱,5173是个不错的选择  

 

上一篇: 处长叫我来的

下一篇: 越美越要钱