需要知道一种简单的方法来为已经存在的http请求添加http标头。
下面是我的中间件代码
public class ProviderStateMiddleware
{
private ITestOutputHelper _outputHelper { get; }
private const string ConsumerName = "test";
private readonly RequestDelegate _next;
private readonly IDictionary<string, Action> _providerStates;
public ProviderStateMiddleware(RequestDelegate next)
{
_next = next;
_providerStates = new Dictionary<string, Action>
{
{
"A session id",
getSessionID
},
};
}
private void getSessionID()
{
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.Value == "/provider-states")
{
this.HandleProviderStatesRequest(context);
await context.Response.WriteAsync(String.Empty);
}
else
{
await this._next(context);
}
}
private void HandleProviderStatesRequest(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
if (context.Request.Method.ToUpper() ==
HttpMethod.Post.ToString().ToUpper() &&
context.Request.Body != null)
{
string jsonRequestBody = String.Empty;
using (var reader = new StreamReader(context.Request.Body,
Encoding.UTF8))
{
jsonRequestBody = reader.ReadToEnd();
}
var providerState = JsonConvert.DeserializeObject<ProviderState>
(jsonRequestBody);
//A null or empty provider state key must be handled
if (providerState != null &&
!String.IsNullOrEmpty(providerState.State) &&
providerState.Consumer == ConsumerName)
{
_providerStates[providerState.State].Invoke();
}
}
}
}
}
我是c#或http中间件的新手,请告诉我在哪里可以添加自定义标头,例如json以下。我在这里阅读了一些帖子,但据我了解并不多。
{Subscriber-id : "1234"}
答案 0 :(得分:0)
HttpResponse.OnStarting
添加要在之前调用的委托 响应头将发送到客户端。
将此代码添加到您的public async Task Invoke(HttpContext context)
函数中:
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("Key", "Value");
return Task.CompletedTask;
});
答案 1 :(得分:0)
这是通过PactVerifierConfig.CustomHeader方法处理的,该方法添加了请求标头。
var config = new PactVerifierConfig
{
Outputters = new List<IOutput>
{
new XUnitOutput(_outputHelper)
},
//Custom header
CustomHeader = new KeyValuePair<string, string>("testId","test123"),
// Output verbose verification logs to the test output
Verbose = true
};