我將服務升級到 .NET Core 6。舊代碼允許用戶發送“ / ”作為 Accept 標頭,并且代碼根據請求回傳正確的回應型別 xml 或 json。版本 6 不再這樣做了。應用程式團隊不想更改他們的代碼,所以我需要知道如何允許“ / ”用于 Accept 標頭,并將回應回傳為 xml 用于 xml 請求和 json 用于 json 請求。
我的 Startup.cs 檔案:
using log4net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Linq;
using AgencyInterfaceSearchCore.Models;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
using AgencyInterfaceSearchCore.Interface;
using AgencyInterfaceSearchCore.Repository;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
namespace AgencyInterfaceSearchCore
{
public class Startup
{
private static readonly ILog _log = LogManager.GetLogger(typeof(Startup));
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static Dictionary<string, string> StatusMapping { get; set; }
public static Dictionary<string, string> EligibilityMapping { get; set; }
public static Dictionary<string, string> ProfileMapping { get; set; }
public static Dictionary<string, string> RedirectMapping { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(name: "v2", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Agency Interface Search Web Service", Version = "v2" });
});
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
}).AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddControllers().AddXmlSerializerFormatters();
// Add Service/Repository
services.AddScoped<IHostBridgeService, HostBridgeService>();
services.Configure<CustomHostBridgeSection>((settings) =>
{
Configuration.GetSection("EligibilityMapping").Bind(settings);
});
StatusMapping = Configuration.GetSection("StatusMapping").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
EligibilityMapping = Configuration.GetSection("EligibilityMapping").GetChildren()
//.Select(item => new KeyValuePair<string, string>(item.Key, item.Value))
.ToDictionary(x => x.Key, x => x.Value);
ProfileMapping = Configuration.GetSection("ProfileMapping").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
RedirectMapping = Configuration.GetSection("RedirectMapping").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
context.Request.EnableBuffering(); //enables repeated reading of request
var initialHeaders = context.Request.Headers;
using (var reader = new StreamReader(
context.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: 1024 * 100, //change 100 to accommodate the biggest request. In this case the size is 100Kb
leaveOpen: true))
{
string body = await reader.ReadToEndAsync();
_log.Info("Original Unescaped Request: " body);
string headerString = "\r\n";
foreach (var item in initialHeaders)
{
if (!string.IsNullOrEmpty(item.ToString()))
{
headerString = item.ToString() "\r\n";
}
}
_log.Info("Original Headers: " headerString);
context.Request.Body.Position = 0;
await next.Invoke();
}
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint(url: "/swagger/v2/swagger.json", name: "Acquire Customer Number Service API V2");
});
_log.Info("Swagger configured as JSON endpoint.");
_log.Info("App Configured");
}
}
}
請求物件:
using System.Runtime.Serialization;
namespace AgencyInterfaceSearchCore.Models
{
[DataContract]
public class AgencyInterfaceSearchRequest
{
[DataMember]
public string AgencyCode { get; set; }
[DataMember]
public string RedirectionCode { get; set; }
[DataMember]
public string CallingApplicationName { get; set; }
[DataMember]
public string FutureUse { get; set; }
}
}
uj5u.com熱心網友回復:
請求標頭中的“接受”表示您希望回應正文中的內容型別,如果您設定:"Accept":"*/*",則表示所有內容型別都可以。如果您想將回應正文的內容型別設定為與請求正文的內容型別相同,只需在控制器中嘗試以下操作:
var ContentType = HttpContext.Request.Headers["Content-Type"];
HttpContext.Response.ContentType = ContentType;
我測驗如下,你可以看到結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487107.html
標籤:C# 。网 asp.net 核心 asp.net-web-api
