我在asp.net(c#)的wcf服务中使用自定义基本身份验证。我想在设置错误的用户名或密码时给出未经授权的自定义错误。
代码概述如:
public class BasicAuthenticationInterceptor : RequestInterceptor
{
MembershipProvider provider;
string realm;
public BasicAuthenticationInterceptor(MembershipProvider provider, string realm)
: base(false)
{
this.provider = provider;
this.realm = realm;
}
protected string Realm
{
get { return realm; }
}
protected MembershipProvider Provider
{
get { return provider; }
}
public override void ProcessRequest(ref RequestContext requestContext)
{
HttpRequestMessageProperty request = (HttpRequestMessageProperty)requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
if (//wrong password)
{
try
{
string errorHtml = "<html><HEAD><TITLE>Request Error</TITLE></HEAD><BODY>" +
"<H1>Error processing request</H1><P>{0}</P></BODY></html>";
XElement response = XElement.Load(new StringReader(
string.Format(errorHtml, "Missing or invalid user key (supply via the Authorization header)")));
Message reply = Message.CreateMessage(MessageVersion.None, null,response);
HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };
responseProperty.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", Realm));
reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
requestContext.Reply(reply);
requestContext = null;
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
}
在此代码中没有给出错误和响应正文设置正确但标题,状态代码等。 响应给200 OK。但是想要401未经授权。
任何人都可以帮忙设置401错误吗?
感谢。
答案 0 :(得分:0)
通过将消息第二个参数(字符串操作)null更新为“action”来解决它我自己,并且它正常工作。
Message reply = Message.CreateMessage(MessageVersion.None, null,response);
updated
Message reply = Message.CreateMessage(MessageVersion.None, "action" ,response);
以HTML格式获取响应说明在我的代码中添加一行
responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";