我有一个.NET MVC项目,项目中使用API控制器来实现REST API。项目中的身份验证基于OwinMiddleware。
以下代码片段用于OwinMiddleware身份验证。
在 startup.cs 文件中,我已经添加了以下代码。
当我使用Postman连续调用API时,发现以下响应: 无法获得任何响应。 连接到baseUrl/api/User?pageNumber=1&pageSize=500时出错。 可能的原因: 服务器无法发送响应: 确保后端正常工作 自签名SSL证书被阻止: 通过在“设置”>“常规”中关闭“SSL证书验证”来解决 代理配置不正确: 确保在“设置”>“代理”中正确配置代理 请求超时: 在“设置”>“常规”中更改请求超时时间 以下是Windows事件日志中的一些异常。
事件代码: 3005 事件消息: 发生了未处理的异常。事件时间: 2019年2月14日 下午7:04:10 事件时间 (UTC): 2019年2月14日 上午8:04:10 事件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标头已发送后附加标头。 at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace) at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values) at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary`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.<Invoke>d__0.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.<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.<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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<Run>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.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step API控制器有以下代码来返回响应。
以下代码片段用于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);
}
当我使用Postman连续调用API时,发现以下响应: 无法获得任何响应。 连接到baseUrl/api/User?pageNumber=1&pageSize=500时出错。 可能的原因: 服务器无法发送响应: 确保后端正常工作 自签名SSL证书被阻止: 通过在“设置”>“常规”中关闭“SSL证书验证”来解决 代理配置不正确: 确保在“设置”>“代理”中正确配置代理 请求超时: 在“设置”>“常规”中更改请求超时时间 以下是Windows事件日志中的一些异常。
事件代码: 3005 事件消息: 发生了未处理的异常。事件时间: 2019年2月14日 下午7:04:10 事件时间 (UTC): 2019年2月14日 上午8:04:10 事件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标头已发送后附加标头。 at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace) at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values) at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary`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.<Invoke>d__0.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.<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.<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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<Run>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.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step 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;