HttpResponse is returning status code 400, after being set to a custom value

StackOverflow https://stackoverflow.com/questions/20473304

  •  30-08-2022
  •  | 
  •  

سؤال

I have the following service method which is called on when the following restful url is given http://xxxxxxxxx/api/checkemail?email={email} If the length of the email exceeds 254 characters then I want to throw an argument out of range exception, which works okay, and overwrite the http response status code which isnt working.

When i execute the url in fiddler, instead of return the status code 94043 (a random number i wanted to use) it returns 400 bad request. Any ideas why?

    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);
    }
هل كانت مفيدة؟

المحلول

Going to use the WebFaultException class. It avoids having to manage the httpresponse object.

    public bool CheckIfUserExists(string email)
    {
        if (email.Length > 254)
        {                
            throw new WebFaultException<string>("{EmailTooLong" + ":" + "Error 94043" + "}", System.Net.HttpStatusCode.BadRequest);
        }
        return DBUtility.CheckIfUserExists(email);
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top