我知道我们无法在RedirectToAction
方法中使用void
,但如何绕过以下方案。请参阅能够很好地解释方案的评论。
public void CertificateVerification(string regNo)
{
try
{
var _dbRegn = _db.StudentRegistrations
.Where(r => r.RegistrationNumber == regNo)
.FirstOrDefault();
//checking if registration exist
if (_dbRegn != null)
{
var _isCertificateIssued = _dbRegn.IsCertificateIssued.Value;
//checking if certificate issued
if (_isCertificateIssued)
{
string FilePath = Server.MapPath("~/Certificates/" + _dbRegn.RegistrationNumber + ".pdf"); ;
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
//if certificate not issued then redirect to specific page
else
{
RedirectToAction("CertificateNotApproved");
}
}
//if registration dont exist redirect to specific page
else
{
RedirectToAction("CertificateDontExist");
}
}
catch (Exception ex)
{
RedirectToAction("CertificateDontExist");
}
}
答案 0 :(得分:2)
重写方法,使其达到你想要的效果
public bool IsCertificateValid(string regNo, string redirectTo)
{
redirectTo = null;
try
{
var _dbRegn = _db.StudentRegistrations
.Where(r => r.RegistrationNumber == regNo)
.FirstOrDefault();
if (_dbRegn != null)
{
var _isCertificateIssued = _dbRegn.IsCertificateIssued.Value;
if (_isCertificateIssued)
{
// unimportant code...
}
else
{
redirectTo = "CertificateNotApproved";
}
}
else
{
redirectTo = "CertificateDontExist";
}
}
catch (Exception ex)
{
redirectTo = "CertificateDontExist";
}
return !string.IsNullOrEmpty(redirectTo);
}
用法:
string redirectTo;
if (!IsCertificateValid(regNo, out redirectTo)
{
return RedirectToAction(redirectTo);
}