如何从任务中获取请求主体和响应主体<;HttpResponseMessage>;在C#中发送异步以登录数据库
我不熟悉web api。有人能告诉我如何从下面提取请求正文和响应正文吗如何从任务中获取请求主体和响应主体<;HttpResponseMessage>;在C#中发送异步以登录数据库,c#,asp.net-web-api,C#,Asp.net Web Api,我不熟悉web api。有人能告诉我如何从下面提取请求正文和响应正文吗 public class TokenValidationHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
public class TokenValidationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpStatusCode statusCode;
string token;
//determine whether a jwt exists or not
if (!TryRetrieveToken(request, out token))
{
statusCode = HttpStatusCode.Unauthorized;
//allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
// want to save into DB both request and response
objSaveRequestResponse.SaveRequestResponse(request, response);
return response;
});
}
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.MessageHandlers.Add(new TokenValidationHandler());
我尝试了请求。内容和回复。标题,但没有运气。
非常感谢示例代码:)这可能会有所帮助
HttpContent requestContent = Request.Content;
string strContent = requestContent.ReadAsStringAsync().Result;
回答也是如此
更新
在@aepot的建议之后
HttpContent requestContent = Request.Content;
string strContent = await responseContent.ReadAsStringAsync();
我在理解你所有的代码时遇到了一些问题,我认为这比你在这里展示的内容更重要。但一般来说,这是获取HttpResponseMessage的内容的方式:
HttpResponseMessage response = //call you method to get the response
string content = await response.Content.ReadAsStringAsync();
您希望查看“响应”而不是“请求”。。。但是你能给我们多介绍一点情况吗?这是如何使用的?我的意思是。。。你能告诉我们这些代码都在哪里使用吗?@caseycrokston请看一看。我更新代码部分好的,是的,这很有帮助。现在。。。你能告诉我们你在哪里调用这个
SendAsync()
方法吗?@CaseyCrookston更新的代码请看一下:)也许我找不到它。但是在SendAsync()
方法中生成的HttpResponseMessage
在哪里处理?wait
看起来比更安全。
HttpResponseMessage response = //call you method to get the response
string content = await response.Content.ReadAsStringAsync();