.Net Core WebApi

这篇具有很好参考价值的文章主要介绍了.Net Core WebApi。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录
  • MiniMalAPi
    • Demo
      • Program.cs
  • Swagger
    • 文档+信息
      • Program.cs
    • API版本控制
      • ApiVersion.cs
      • Version1Controller.cs
      • Program.cs
    • 生成注释
  • 解决跨域
  • .Net 后台请求封装
  • 返回数据压缩
    • 默认压缩
    • Gzip压缩
  • 缓存
    • 接口缓存
    • 静态文件缓存

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");
    }
}); 

文章来源地址https://www.toymoban.com/news/detail-633175.html

到了这里,关于.Net Core WebApi的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • .net core 配置swagger

    要在 ASP.NET Core 中配置 Swagger,您需要遵循以下步骤: 添加 Swagger NuGet 包:将 Swashbuckle.AspNetCore NuGet 包添加到项目中。 在 Startup.cs 文件中进行配置: 在上述代码中,我们通过调用 services.AddSwaggerGen 方法来配置 Swagger。您可以使用这个方法来设置 API 的标题、版本、描述等信息

    2024年02月13日
    浏览(22)
  • .net core swagger分组与分组隐藏

    swagger接口一多,还是需要分个组比较妥当,以图文方式看更直观 定义分组 添加分组 看板展示 两个分组   我要对v1组进行隐藏,首先先了解一下  ApplicationModel ApplicationModel描述了应用中的各种对象和行为,包含Application、Controller、Action、Parameter、Router、Page、Property、Filter等

    2024年02月08日
    浏览(26)
  • .NET Core WebAPI中封装Swagger配置

    创建一个Utility/SwaggerExt文件夹,添加一个类 在SwaggerExt类中添加方法,将相关配置添写入 调用封装的方法

    2024年02月20日
    浏览(30)
  • .NET Core WebAPI中使用Swagger(完整教程)

    1.1-什么是Swagger? Swagger是一个规范且完整的框架,用于生成、描述、调试和可视化Restfull风格的Web服务。 Swagger的目标是对Rest API定义一个标准且和语言无关的接口,可以让人和计算机拥有无需访问源码、文档或网络流量监控就可以发现和连接服务的能力。当通过Swagger进行正确

    2024年02月14日
    浏览(21)
  • .NET Core WebAPI中使用swagger版本控制,添加注释

    在代码中添加注释 在项目属性中生成API文档 在Program中注册Swagger服务并配置文档信息

    2024年02月20日
    浏览(32)
  • .NET Core WebAPI项目部署iis后Swagger 404问题解决

    之前做了一个WebAPI的项目,我在文章中写到的是Docker方式部署,然后考虑到很多初学者用的是iis,下面讲解下iis如何部署WebAPI项目。 iis ASPNETCoreModuleV2 重点 .NET Core Runtime iis的配置这里就不讲了,主要讲解.NET Core项目部署之后Swagger无法访问问题。 ASPNETCoreModuleV2 安装: https:/

    2024年03月09日
    浏览(34)
  • Asp .Net Core 系列:基于 Swashbuckle.AspNetCore 包 集成 Swagger

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。它提供了一种规范的方式来定义、构建和文档化 RESTful Web 服务,使客户端能够发现和理解各种服务的功能。Swagger 的目标是使部署管理和使用功能强大的 API 从未如此简单。 Swagger 提供了

    2024年01月18日
    浏览(44)
  • ASP.NET Core Web API入门之二:Swagger详细使用&路由设置

    本篇文章是Swagger的详细使用,续上篇ASP.NET Core Web API入门之一:创建新项目。 Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务的接口文档。 根据在代码中使用自定义的注解来生成接口文档,这个在前后端分离的项目中很重要。这样做的

    2024年02月15日
    浏览(36)
  • .net core的Knife4jUI,让swagger更精致

    要在 .NET Core 中使用 IGeekFan.AspNetCore.Knife4jUI,您可以按照以下步骤进行配置: 首先,安装 IGeekFan.AspNetCore.Knife4jUI NuGet 包。可以通过 Visual Studio 的 NuGet 包管理器或者 .NET CLI 进行安装。 在 Startup.cs 文件的 ConfigureServices 方法中,添加以下代码,来配置 IGeekFan.AspNetCore.Knife4jUI: 在

    2024年02月13日
    浏览(22)
  • 在IIS上部署你的ASP.NET Core Web Api项目及Swagger

    与ASP.NET时代不同,ASP.NET Core不再是由IIS工作进程(w3wp.exe)托管,而是使用自托管Web服务器(Kestrel)运行,IIS则是作为反向代理的角色转发请求到Kestrel不同端口的ASP.NET Core程序中,随后就将接收到的请求推送至中间件管道中去,处理完你的请求和相关业务逻辑之后再将HTTP响

    2024年02月10日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包