HttpResponse在设置为自定义值后返回状态代码400

时间:2013-12-09 14:38:55

标签: c# wcf httpcontext

我有以下服务方法,当给出以下restful url时调用http://xxxxxxxxx/api/checkemail?email={email}如果电子邮件的长度超过254个字符,那么我想抛出一个超出范围异常的参数,这没关系,并覆盖不起作用的http响应状态代码。

当我在fiddler中执行url时,它不返回状态代码94043(我想要使用的随机数),而是返回400错误请求。有什么想法吗?

    public bool CheckIfUserExists(string email)
    {
        if (email.Length > 254)
        {
            HttpContext.Current.Response.StatusCode = 94043;
            HttpContext.Current.Response.Status = "The email exceeds the maximum character limit";    
            throw new ArgumentOutOfRangeException("Email", "The email address is greater than 254 characters");
        }
        return CheckIfUserExists(email);
    }

1 个答案:

答案 0 :(得分:1)

要使用WebFaultException类。它避免了必须管理httpresponse对象。

    public bool CheckIfUserExists(string email)
    {
        if (email.Length > 254)
        {                
            throw new WebFaultException<string>("{EmailTooLong" + ":" + "Error 94043" + "}", System.Net.HttpStatusCode.BadRequest);
        }
        return DBUtility.CheckIfUserExists(email);
    }