WCF WebApi,处理 IsThisTaken 查询的正确方法是什么?
我正在编写 WCF webapi 应用程序,需要检查电子邮件地址是否被占用。这需要是客户端代码在尝试 PUT
之前可以执行的查询。
因此,我想做的是将 HEAD
与 HTTP 状态代码结合使用。我有点不确定如何去做,因为它需要一个简单的是/否响应。因此,我使用 HttpResponseExceptions
返回相关的状态代码。
[WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
[RequireAuthorisation]
public void IsEmailAddressTaken(string email)
{
if (!Regex.IsMatch(email, Regexes.EmailPattern))
{
throw new RestValidationFailureException("email", "invalid email address");
}
if (_repository.IsEmailAddressTaken(email))
{
throw new HttpResponseException(HttpStatusCode.OK);
}
throw new HttpResponseException(HttpStatusCode.NoContent);
}
这对我来说“闻起来”不太对劲。
我是否要以正确的方式进行这种是/否操作?
I am in the process of writing a WCF webapi application and have a need to check whether an email address is taken or not. This needs to be a query the client-side code can do before attempting a PUT
.
So, what I'm trying to do is use HEAD
in conjunction with HTTP status codes. I am a little unsure how to go about doing that as it's a simple yes/no response which is required. So, I've used HttpResponseExceptions
to return the relevant status code.
[WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
[RequireAuthorisation]
public void IsEmailAddressTaken(string email)
{
if (!Regex.IsMatch(email, Regexes.EmailPattern))
{
throw new RestValidationFailureException("email", "invalid email address");
}
if (_repository.IsEmailAddressTaken(email))
{
throw new HttpResponseException(HttpStatusCode.OK);
}
throw new HttpResponseException(HttpStatusCode.NoContent);
}
This just doesn't "smell" right to me.
am I going about doing this kind of yes/no operation the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是返回 HttpResponseMessage 而不是抛出异常。
您的
RestValidationFailureException
是否在任何地方得到处理?如果不是,则会产生 500 状态代码,这似乎不够。My suggestion is to return a
HttpResponseMessage
instead of throwing exceptions.Is your
RestValidationFailureException
being handled anywhere? If not, it will result in a 500 status code, which does not seem adequate.我认为对于“存在”返回 OK ,对于“不存在”返回 404 就可以了
I think it would be ok to just return OK for "exists" and 404 for "does not exist"