我有一个.NET MVC项目,并且我在该项目内部使用了用于REST API的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(字符串名称,字符串值,布尔值替换)在Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(字符串键,
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(任务任务)在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(任务任务)在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务))在Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.d__5.MoveNext()---从上一个引发异常的位置开始的堆栈跟踪---在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) ),位于Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.d__2.MoveNext()的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)-从引发异常的上一位置开始的堆栈结束跟踪-在System.Runtime.ExceptionServices.ExceptionDispatchInfo中。Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)处的Throw()在System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() IExecutionStep步骤,布尔值和已同步完成)
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句