.net - 无法获得任何响应 - 发送 HTTP 标头后服务器无法附加标头
问题描述
我有一个 .NET MVC 项目,我在项目中使用 API 控制器来获取 REST API。项目中使用的身份验证基于 OwinMiddleware。
以下代码用于 OwinMiddleware 中进行身份验证
var authValue = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authValue) && (authValue.StartsWith("Basic ")))
{
authValue = authValue.Substring(6).Trim();
authValue = Encoding.UTF8.GetString(Convert.FromBase64String(authValue));
var credentials = authValue.Split(":".ToCharArray());
var signInStatus = await _signinManager.PasswordSignInAsync(credentials[0], credentials[1], false, false);
switch (signInStatus)
{
case Microsoft.AspNet.Identity.Owin.SignInStatus.Success:
var user = await _userManager.FindByNameAsync(credentials[0]);
var identity = await _signinManager.CreateUserIdentityAsync(user);
context.Request.User = new ClaimsPrincipal(identity);
await base.Next.Invoke(context);
break;
default:
context.Response.StatusCode = 401;
// an aobject representing error
var res = GetResposeData()
var format = GetResponseContentType(context.Request);
var data = ParseToString(res , format);
var dataByte = Encoding.UTF8.GetBytes(data);
context.Response.ContentType = GetContentType(format);
context.Response.Body.Write(dataByte, 0, dataByte.Length);
break;
}
}
在 startup.cs 我添加了以下代码
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<CustomSignInManager>());
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<CustomUserManager>());
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/index"),
Provider = new CookieAuthenticationProvider()
{
OnApplyRedirect = ctx =>
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
});
app.UseAutofacMiddleware(AutofacConfig.Container);
}
当我使用邮递员连续调用 API 时,发现以下响应
无法得到任何回应。连接到 baseUrl/api/User?pageNumber=1&pageSize=500 时出错。为什么会发生这种情况:服务器无法发送响应:确保后端正常工作自签名 SSL 证书被阻止:通过在设置 > 常规代理配置不正确中关闭“SSL 证书验证”来修复此问题确保代理在设置>代理请求超时中正确配置:在设置>常规中更改请求超时
以下是 Windows 事件日志中的一些例外情况。
事件代码:3005 事件消息:发生未处理的异常。事件时间:2/14/2019 7:04:10 PM 事件时间 (UTC):2/14/2019 8:04:10 AM 事件 ID:22548ff89e3744adbfd5c3e2b3b66ef4 事件顺序:5 事件发生:1 事件详细代码:0 应用程序信息: 应用程序域:/LM/W3SVC/1/ROOT/XYZ-2-131946050074629312 信任级别:完整应用程序虚拟路径:/XYZ 应用程序路径:C:\inetpub\wwwroot\xyz\ 机器名:ABC 进程信息:进程ID: 15228 进程名称:w3wp.exe 帐户名称:IIS APPPOOL\DefaultAppPool 异常信息:异常类型:HttpException 异常消息:发送 HTTP 标头后服务器无法附加标头。在 System.Web.HttpHeaderCollection.SetHeader(字符串名称,字符串值,
2 headers, String key, String[] values) at Microsoft.Owin.Infrastructure.ChunkingCookieManager.AppendResponseCookie(IOwinContext context, String key, String value, CookieOptions options) at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__f.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__b.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseAsync>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware
1.d__0.MoveNext() --- 从先前引发异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务)在 Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.<Invoke>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware
2.d__5.MoveNext() --- 从先前引发异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务)在 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.d__5.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.d__2.MoveNext() --- 堆栈跟踪从之前抛出异常的位置结束---在 System.Runtime。ExceptionServices.ExceptionDispatchInfo.Throw() 在 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) 在 System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 在 System.Web。 HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
API 控制器具有以下代码来返回响应
// create new response
// format can be json or xml
var response = new HttpResponseMessage()
{
Content = new StringContent(data, Encoding.UTF8, format),
StatusCode = httpStatus
};
//if last modified available
// some date value
if (lastUpdated != null)
response.Content.Headers.LastModified = lastUpdated;
return response;
解决方案
您混合了 webapi 和 MVC 身份验证。将您的代码 startup.cs 更改为以下内容:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<CustomSignInManager>());
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<CustomUserManager>());
app.MapWhen((context) => {
return !IsApiRequest(context.Request);
}, (mvcApp) => {
mvcApp.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/index"),
Provider = new CookieAuthenticationProvider()
});
});
app.UseAutofacMiddleware(AutofacConfig.Container);
}
推荐阅读
- angular - 嵌套表单:提交时不验证内部表单
- assembly - nasm 段错误 macos mojave 10.14.1
- arrays - Swift:在数组中追加项目的算法
- javascript - VS Code 如何将 HTML 组合成 .JS 文件?
- css - 图像不适合引导程序 4 中的轮播
- jtable - 如何减少自定义 DefaultTableCellRenderer(斑马色表)的 cpu 资源?
- node.js - Telegram 机器人的循环问题
- python-3.x - 具有 for 循环值的多个浮点输入()
- javascript - 用 javascript 模板文字推断变量的正确语法?
- java - 更新对象列表中对象的值