【问题标题】:HttpResponse is returning status code 400, after being set to a custom valueHttpResponse 在设置为自定义值后返回状态码 400
【发布时间】:2013-12-09 14:38:54
【问题描述】:

我有以下服务方法,当给定以下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);
    }

【问题讨论】:

  • 它可能不会让你这样做,因为你不应该发明自己的不属于 Http 规范的状态代码,我猜框架会强制执行这一点。通常,4xx 表示某种用户错误,因此您应该返回 400 bad request 或其他一些 4xx 错误代码

标签: c# wcf httpcontext


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多