c# - 如何在 Restful 响应中保持区分大小写?

标签 c# asp.net-core asp.net-core-webapi

如何在 Restful 响应中保持区分大小写?

我的 friend 提示 RESTful 响应区分大小写

enter image description here

文件*.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <UserSecretsId>4942e08e-0489-4b66-ab36-7c1376ecb8a8</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AWSSDK" Version="2.3.55.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0-preview.8.20407.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0-preview.8.20407.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0-preview.8.20407.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Identity.Core" Version="5.0.0-preview.8.20414.8" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.0-preview.8.20419.1" />
    <PackageReference Include="MimeKit" Version="2.9.1" />
    <PackageReference Include="NAudio" Version="1.10.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="NUnit" Version="3.12.0" />
    <PackageReference Include="RestSharp" Version="106.11.5-alpha.0.18" />
    <PackageReference Include="SendGrid" Version="9.21.0" />
    <PackageReference Include="Serilog" Version="2.10.0-dev-01240" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.5.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.5.1" />

    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />

    <PackageReference Include="System.ServiceModel.Syndication" Version="5.0.0-preview.8.20407.11" />
    <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0-preview.8.20407.11" />
    <PackageReference Include="Twilio" Version="5.46.2" />
    <PackageReference Include="Twilio.AspNet.Core" Version="5.33.1" />
  </ItemGroup>


</Project>

        /// <summary>
        /// GET: http://localhost:5002/TrustedPerson/5
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<TrustedPerson>> ViewTrustedPerson(int id)
        {
            var item = await _db.TrustedPeople.FindAsync(id);
            if (item == null)
            {
                return NotFound();
            }   
            return item;
        }

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using shadow.Data;
using shadow.Services;
using System.Text;
using Microsoft.Extensions.FileProviders;
using System.IO;
using shadow.Models;
using Microsoft.AspNetCore.Authorization;

namespace shadow
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddHttpContextAccessor();
            //services.AddCors();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            });

            services.AddSingleton<IUriService>(o =>
            {
                var accessor = o.GetRequiredService<IHttpContextAccessor>();
                var request = accessor.HttpContext.Request;
                var uri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent());
                return new UriService(uri);
            });
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                //options.Password.RequireDigit = true;
                //options.Password.RequireLowercase = true;
                options.Password.RequiredLength = 6;
            }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
            services
                .AddAuthentication(auth =>
                {
                    auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidAudience = Configuration["AuthSettings:Audience"],
                        ValidIssuer = Configuration["AuthSettings:Issuer"],
                        RequireExpirationTime = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthSettings:Key"])),
                        ValidateIssuerSigningKey = true
                    };
                });

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

            services.AddScoped<IUserService, UserService>();
            services.AddTransient<IMailService, SendGridMailService>();
            services.AddControllers();
            services.AddRazorPages();
            services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseHttpsRedirection();
            app.UseRouting();
            // app.UseCors(options => options.WithOrigins("http://localhost:4200")
            //.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            app.UseAuthorization();
            
            // Server: https://shorten.news/static-file/content/10992.mp3
            // Local: http://localhost:5000/static-file/content/10992.mp3
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                // Path.Combine(env.ContentRootPath, @"c:\audio\")),
                Path.Combine(@"c:\audio\")),
                RequestPath = "/static-file"
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

}

模型

using System;

#nullable disable

namespace shadow.Models
{
    public partial class TrustedPerson
    {
        public int Id { get; set; }
        public string Fullname { get; set; }
        public string AliasName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber1 { get; set; }
        public string PhoneNumber2 { get; set; }
        public string PhoneNumber3 { get; set; }
        public int? RelationshipId { get; set; }
        public string About { get; set; }
        public int? AvatarId { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Modified { get; set; }
    }
}

回复如

{
    "id": 1,
    "fullname": "Do Xxx Xx",
    "aliasName": "Xx ham",
    "email": "xxdn@xxsolutioxx.io",
    "phoneNumber1": "0989878776",
    "phoneNumber2": "0989878777",
    "phoneNumber3": "0989878778",
    "relationshipId": 3,
    "about": "Dep trai",
    "avatarId": 42,
    "created": "2020-09-05T10:34:39.427",
    "modified": null
}

我的 friend 想要

{
    "Id": 1,
    "Fullname": "Do Xxx Xx",
    "AliasName": "Xx ham",
    "Email": "xxdn@xxsolutioxx.io",
    "PhoneNumber1": "0989878776",
    "PhoneNumber2": "0989878777",
    "PhoneNumber3": "0989878778",
    "RelationshipId": 3,
    "About": "Dep trai",
    "AvatarId": 42,
    "Created": "2020-09-05T10:34:39.427",
    "Modified": null
}

(2)

(2) 是最佳实践吗?

如何像C#模型一样在RESTful响应的key中保持大小写敏感?

最佳答案

添加这一行

services.AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; });

关于c# - 如何在 Restful 响应中保持区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63787119/

相关文章:

asp.net - ASP.NET 5 中的全局异常处理

c# - 如何在 ASP.NET Core Web API 中的每个方法中进行模型验证?

c# - VS2017 .NetCore 2.0 API - 无法加载文件或程序集 Microsoft.AspNetCore.Hosting.Abstractions

c# - 如果在 C# 中不存在则插入

c# - 在 asp.net Portable.Licensing 中,.WithMaximumUtilization(1) 的含义和用途是什么?

c# - 无法将模型值分配给 Razor 页面中的参数

Azure AAD - 受众无效

c# - 如何使用 lambda 表达式作为参数?

c# - 启用多个网络适配器时 HttpWebRequest 超时

c# - Net Core 错误名称 'Ok' 在当前上下文中不存在