3 回答

TA貢獻(xiàn)1995條經(jīng)驗 獲得超2個贊
如果要在asp.net MVC網(wǎng)站中添加asp.net WebApi,則可能要對某些請求進(jìn)行未經(jīng)授權(quán)的響應(yīng)。但是隨后ASP.NET基礎(chǔ)結(jié)構(gòu)開始起作用,當(dāng)您嘗試將響應(yīng)狀態(tài)代碼設(shè)置為HttpStatusCode時。未經(jīng)授權(quán),您將獲得302重定向到登錄頁面。
如果您在此處使用asp.net身份和基于owin的身份驗證,則可以使用以下代碼來解決該問題:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider()
{
OnApplyRedirect = ctx =>
{
if (!IsApiRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
private static bool IsApiRequest(IOwinRequest request)
{
string apiPath = VirtualPathUtility.ToAbsolute("~/api/");
return request.Uri.LocalPath.StartsWith(apiPath);
}
- 3 回答
- 0 關(guān)注
- 1618 瀏覽
添加回答
舉報