首页 > 其他分享 >.Net Core WebApi

.Net Core WebApi

时间:2023-08-08 18:55:36浏览次数:30  
标签:WebApi Core contentType string headers application client Net null

目录

MiniMalAPi

  • 最小的api, 请求都写在Program.cs中, 可以做微服务

Demo

Program.cs

//基本请求
app.MapGet("/GetTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapPost("/PostTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapPut("/PutTest", () => new { result = "123", code = 200 }).WithTags("General Request");
app.MapDelete("DeletePut", () => new { result = "123", code = 200 }).WithTags("General Request");

//注入
app.MapGet("/GetTestIoc", (IStudent student,IWrite pen) => student.Calligraphy(pen)).WithTags("Ioc");
app.MapGet("/GetTestIocById", (IStudent student,IWrite pen,int? id) => student.Calligraphy(pen)).WithTags("Ioc");
app.MapPost("/GetTestIocByObject", (IStudent student,IWrite pen,Result result) => student.Calligraphy(pen)).WithTags("Ioc");

Swagger

文档+信息

Program.cs

builder.Services.AddSwaggerGen(setup =>
{
    setup.SwaggerDoc("V1", new()
    {
        Title = "qfccc",
        Version = "V1",
        Description = "qfccc description",
    });
});

app.UseSwaggerUI(setup =>
{
    setup.SwaggerEndpoint("/swagger/V1/swagger.json", "V1");
});

API版本控制

  • 该例子仅供参考

ApiVersion.cs

namespace WebApiDemo.VersionControl
{
    public class ApiVersion
    {
        public static string? Version1;
        public static string? Version2;
        public static string? Version3;
        public static string? Version4;
        public static string? Version5;
    }
}

Version1Controller.cs

  • 这里其他版本api 修改ApiVersion.Version1即可
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiDemo.VersionControl;

namespace WebApiDemo.Controllers
{
    [ApiExplorerSettings(GroupName = nameof(ApiVersion.Version1))]
    [Route($"api/[controller]/[action]/api.{nameof(ApiVersion.Version1)}")]
    [ApiController]
    public class Version1Controller : ControllerBase
    {

        [HttpGet]
        public IActionResult GetString() => new JsonResult(new { result = "Success" });

        [HttpPost]
        public IActionResult PostString() => new JsonResult(new { result = "Success" });

        [HttpPut]
        public IActionResult PutString() => new JsonResult(new { result = "Success" });

        [HttpDelete]
        public IActionResult DeleteString() => new JsonResult(new { result = "Success" });
    }
}

Program.cs

builder.Services.AddSwaggerGen(setup =>
{
    foreach (var field in typeof(ApiVersion).GetFields())
    {
        setup.SwaggerDoc(field.Name, new()
        {
            Title = "qfccc",
            Version = field.Name,
            Description = $"qfccc api {field.Name}",
        });
    }
});

app.UseSwaggerUI(setup =>
{
    foreach (var field in typeof(ApiVersion).GetFields())
    { 
        setup.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", field.Name);
    }
});

生成注释

  1. 项目点击右键 -> 属性 -> 输出 -> 勾选(文档文件)
  2. 在AddSwaggerGen中间件添加下方代码
string? basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
if(basePath is not null)
{
    string apiPath = Path.Combine(basePath, "项目名称.xml");
    setup.IncludeXmlComments(apiPath);
}

解决跨域

  1. 调用方调用自己后台,然后用后台请求目标接口解决跨域
  2. 服务器支持跨域请求
    • 在Action中添加这行代码:
    • HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  3. 使用ActionFilter 实现过滤器,代码与上方一致, 然后在Program.cs 文件中全局注册一下该过滤器,但是不支持Post,Put,Delete这种请求
  4. 所有请求都支持跨域可以在Program.cs中增加下方代码:
builder.Services.AddCors( setup =>
{
    setup.AddPolicy("SolveCrossOrigin", policy =>
    {
        policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
    });
});


app.UseCors("SolveCrossOrigin");

.Net 后台请求封装

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NET5WebApplication.Utility
{
    public static class HttpClientHelper
    {
        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new System.Net.Http.HttpClient())
            {
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static T HttpPost<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            return HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<T> HttpPostAsync<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
            return res.ToEntity<T>();
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T HttpGet<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            return HttpGet(url, contentType, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<T> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            var res = await HttpGetAsync(url, contentType, headers);
            return res.ToEntity<T>();
        }
    }

    public static class HttpExtension
    {
        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(this System.Net.Http.HttpClient client, string url, string contentType = "application/json",
                                     Dictionary<string, string> headers = null)
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            if (contentType != null)
                client.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="timeOut"></param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static string HttpPost(this System.Net.Http.HttpClient client, string url, string postData = null,
                                      string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                if (contentType != null)
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                if (contentType != null)
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = await client.PostAsync(url, httpContent);
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static T HttpPost<T>(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            return client.HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>
        /// <returns></returns>
        public static async Task<T> HttpPostAsync<T>(this System.Net.Http.HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            var res = await client.HttpPostAsync(url, postData, contentType, timeOut, headers);
            return res.ToEntity<T>();
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static T HttpGet<T>(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            return client.HttpGet(url, contentType, headers).ToEntity<T>();
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static async Task<T> HttpGetAsync<T>(this System.Net.Http.HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            var res = await client.HttpGetAsync(url, contentType, headers);
            return res.ToEntity<T>();
        }
    }

    public static class JsonExtends
    {
        public static T ToEntity<T>(this string val)
        {
            return JsonConvert.DeserializeObject<T>(val);
        }
        public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
        {
            return JsonConvert.SerializeObject(entity, formatting);
        }
    }
}

返回数据压缩

  • 在Program.cs中添加下面代码

默认压缩

builder.Services.AddResponseCompression();
app.UseResponseCompression();

Gzip压缩

builder.Services.AddResponseCompression(config =>
{
    config.Providers.Add<GzipCompressionProvider>();
});

builder.Services.Configure<GzipCompressionProviderOptions>(config =>
{
    config.Level = CompressionLevel.SmallestSize;
});

缓存

接口缓存

  • 使用特性或者直接在返回头中添加Cache-Control效果一样
[HttpGet]
[ResponseCache(Duration = 600)]
public IActionResult GetString() => new JsonResult(new { result = "Success" });

[HttpGet]
public IActionResult GetStringEx() 
{
    HttpContext.Response.Headers.Add("Cache-Control", "public,max-age=600");
    return new JsonResult(new { result = "Success" });
}

静态文件缓存

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = Prepare =>
    {
        Prepare.Context.Response.Headers.Add(HeaderNames.CacheControl, "public,max-age=600");
    }
}); 

标签:WebApi,Core,contentType,string,headers,application,client,Net,null
From: https://www.cnblogs.com/qfccc/p/17615157.html

相关文章

  • Docker(.Net6) 环境下使用 Haukcode.WkHtmlToPdfDotNet
     背景: 项目使用的是.Net6+Docker,需要将数据生成PDF保存到第三方文件存储服务器上。引用NuGet:Haukcode.WkHtmlToPdfDotNet 这个插件还是满好用的,支持Windows、Docker.可以直接通过Url转PDF,也可以通过Html字符,生成PDF.官方地址:https://github.com/Hak......
  • 在windows上使用_netrc文件让Git记住用户名和密码(Linux文件名为.netrc)
    windowsnetrc文件是什么。根据我搜索到的结果,windowsnetrc文件是一种用于保存网络身份验证信息的文件,例如用户名和密码。它可以被一些命令行工具和应用程序使用,比如Git、curl、ftp等。windowsnetrc文件的格式如下:machine<hostname>login<username>password<password>......
  • Log4netHelper, 支持自定义日志文件生成间隔
    usinglog4net;usinglog4net.Appender;usinglog4net.Config;usinglog4net.Repository;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingstaticlog4net.Appender.FileAppender;namespa......
  • 记一次 .NET某报关系统 非托管泄露分析
    一:背景1.讲故事前段时间有位朋友找到我,说他的程序内存会出现暴涨,让我看下是怎么事情?而且还告诉我是在Linux环境下,说实话在Linux上分析.NET程序难度会很大,难度大的原因在于Linux上的各种开源工具主要是针对C/C++,和.NET一毛钱关系都没有,说到底微软在Linux上的调试领域支......
  • 掌握.NET多线程编程技术
    当涉及到处理并发任务、提高程序性能以及充分利用多核处理器时,.NET多线程编程技术就变得至关重要。在本篇博客中,我将为您介绍一些.NET多线程编程的基本概念和技术,并附上一些示例代码来帮助您更好地理解。为什么使用多线程编程?多线程编程允许在同一进程中同时执行多个线程,从而充分利......
  • ASP.NET Core 中的显示和编辑器模板
    显示模板和编辑器模板指定了自定义类型的用户界面布局。考虑下列 Address 模型:C#复制 publicclassAddress{publicintId{get;set;}publicstringFirstName{get;set;}=null!;publicstringMiddleName{get;set;}=null!;publicst......
  • C#/.NET/.NET Core优秀项目和框架每周精选(坑已挖,欢迎大家踊跃提交PR或者Issues中留言)
    思维导航前言项目地址项目分类(善用Ctrl+F)项目列表加入DotNetGuide技术交流群前言注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯......
  • 第五节:EF Core中的三类事务(SaveChanges、DbContextTransaction、TransactionScope)
    第五节:EFCore中的三类事务(SaveChanges、DbContextTransaction、TransactionScope)原文链接:https://blog.csdn.net/weixin_30954265/article/details/101542615?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~Rate-1-10154......
  • .NET5从零基础到精通:全面掌握.NET5开发技能
    C#版本新语法-官网:C#7:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7C#8:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-8C#9:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-9一、C#6新语法1.1-自动属性初始......
  • EF Core事务
    EFCore事务原文链接:https://blog.csdn.net/m0_47659279/article/details/119929767EFCore事务EFCore提供了SaveChange方法,可以把数据操作好之后再统一调用SaveChange方法,这样就实现了简单的事务功能如果需要多个SaveChange形成一个事务,就是说多个SaveChange要么全部成......