ServiceStack服务正在重定向到MVC表单登录页
本文关键字:MVC 表单 登录 重定向 服务 ServiceStack | 更新日期: 2024-09-23 18:25:42
我在ServiceStack服务上写了一些测试,这些服务需要使用自定义CredentialAuthenticationProvider进行身份验证。
如果我通过不使用servicestack进行身份验证来创建测试,我会得到一个序列化错误,而不是401错误。序列化错误是因为服务正在重定向到MVC登录HTML页。
当调用在serviceStack服务的/api/路径上时,如何防止重定向到MVC,从而使服务返回401?
[TestMethod]
public void DeleteUser_not_authenticated()
{
var client = new JsonServiceClient(STR_APIURL);
var resp1 = client.Post(new Auth() { UserName = "user", Password = "***" });
Assert.IsTrue(resp1.UserName == "user");
var user = client.Get(new GetSupportUser { Email = "test@gmail.com" });
client.Post(new Auth { provider = "logout" });
try
{
var resp = client.Delete(user);
}
catch (HttpException e)
{
Assert.IsTrue(e.GetHttpCode() == 401);
}
}
编辑
根据Mythz的建议,我在global.aspx中尝试过,但这并没有阻止重定向:
protected void Application_EndRequest(object src, EventArgs e)
{
ServiceStack.MiniProfiler.Profiler.Stop();
var ctx = (HttpApplication)src;
if (ctx.Request.Path.Contains("/api/"))
ctx.Response.SuppressFormsAuthenticationRedirect = true;
}
如果使用.NET 4.5,可以禁用内置身份验证重定向通过设置HttpResponse.SuppressFormsAuthenticationRedirect=true
,您可以将其添加到Global.asax.cs:中
protected void Application_EndRequest(Object sender, EventArgs e)
{
var ctx = (HttpApplication)sender;
var suppressForPath = ctx.Request.PathInfo.StartsWith("/api");
ctx.Response.SuppressFormsAuthenticationRedirect = suppressForPath;
}
有关ASP.NET的早期版本,请参阅表单劫持预防上的ServiceStacks文档,以注册自定义SuppressFormsAuthenticationRedirectModule
IHtptModule来防止这种情况。
我将@mythz答案更改为Begin_Request而不是End_Request,现在它阻止重定向到表单身份验证并返回401响应。
protected void Application_BeginRequest(object src, EventArgs e)
{
var ctx = (HttpApplication) src;
var suppressForPath =ctx.Request.Path.StartsWith("/api");
ctx.Response.SuppressFormsAuthenticationRedirect = suppressForPath;
}