如何捕捉异常' ex'在C#中给出http响应

时间:2016-10-17 10:30:04

标签: c# try-catch jwt

我想抓住前任。所以,我可以返回错误代码值

任何人都可以帮助我吗?

public string Decrypt(string cipherText, string sid)
{
    RNCryptor.Decryptor D = new Decryptor();
    string DecryptedString = "";
    int errcode = 0;
    if (Prod == false)
    {
        DecryptedString = cipherText;
    }
    else
    {
    try
    {
        DecryptedString = D.Decrypt(cipherText, sid + SigningKey);
    }
    catch (Exception ex)
    {
        // i want to return errcode 601 to give my response to HTTP
    }
    }
    return DecryptedString.Trim();
}

这是我的另一个代码:

if (ErrCode < 0)
{
    string errMessage = "Decrypt error";
    return Content((HttpStatusCode)(ErrCode * (-1)),errMessage);
}

这是使用我的Decrypt方法的地方

public dynamic GetPikachu(string sid, FormDataCollection form)
    {
        string StrPikachu = Decrypt(form.Get("pikachu"), sid);
        return JsonConvert.DeserializeObject<dynamic>(StrPikachu);
    }

1 个答案:

答案 0 :(得分:0)

在Decrypt方法中执行所需操作的最简单方法是抛出:

throw new HttpResponseException((HttpStatusCode)601);

然而,最简单的往往不是正确的方法。你可以改变你的:

public string Decrypt(string cipherText, string sid)

bool TryDecrypt(string cipherText, string sid, out string result)

并在异常处理程序中返回false。然后在控制器中处理此值。