0
控制器代碼:在MVC4自定義驗證碼圖片刷新
public class CaptchaImageResult : ActionResult
{
public string GetCaptchaString(int length)
{
int intZero = '0';
int intNine = '9';
int intA = 'A';
int intZ = 'Z';
int intCount = 0;
int intRandomNumber = 0;
string strCaptchaString = "";
Random random = new Random(System.DateTime.Now.Millisecond);
while (intCount < length)
{
intRandomNumber = random.Next(intZero, intZ);
if (((intRandomNumber >= intZero) && (intRandomNumber <= intNine) || (intRandomNumber >= intA) && (intRandomNumber <= intZ)))
{
strCaptchaString = strCaptchaString + (char)intRandomNumber;
intCount = intCount + 1;
}
}
return strCaptchaString;
}
public override void ExecuteResult(ControllerContext context)
{
Bitmap bmp = new Bitmap(100, 30);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Navy);
string randomString = GetCaptchaString(6);
context.HttpContext.Session["captchastring"] = randomString;
g.DrawString(randomString, new Font("Courier", 16), new SolidBrush(Color.WhiteSmoke), 2, 2);
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "image/jpeg";
bmp.Save(response.OutputStream, ImageFormat.Jpeg);
bmp.Dispose();
}
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public CaptchaImageResult ShowCaptchaImage(string random)
{
return new CaptchaImageResult();
}
在查看我的代碼是:
<img id="CaptchaImg" src="@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })" alt="" />
<img src="~/Content/images/refresh-ico.ico" style="cursor: pointer;" id="refresh" height="30" width="30" alt="refresh" />
在刷新圖片請執行以下jQuery代碼:
$("#refresh").click(function() {
$.ajax({
type: "GET",
url: '@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })',
contentType: "image/png",
cache: false,
success: function (data) {
debugger;
alert(data);
var img = $('<img id="CaptchaImg" alt="" '); //Equivalent: $(document.createElement('img'))
img.attr('src', '@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })');
//$("#test").html('');
img.appendTo('#test');
}
});
});
圖像不清爽。請幫忙。 我使用OutputCache false並每次發送帶查詢字符串的唯一URL。 但沒有成功。
'ShowCatpchaImage'的結果是一個'image/jpeg'內容類型。不是文本,您不能將'img'標記的src'屬性設置爲二進制數據,它必須是圖像的URL。 – Snixtor
我使用以下代碼設置網址: img.attr('src','@ Url.Action(「ShowCaptchaImage」,「Login」,new {random = Guid.NewGuid()。ToString()})') ; 請建議做些什麼。 –
實際上現在我看看它,'@ Url.Action'確實返回一個URL,或者應該。也許你的JavaScript沒有被剃刀引擎解析,所以'@ Url.Action'指令沒有被解析。你在做任何**調試嗎?刷新點擊處理程序正在執行?它是否發送請求?它發送請求的地址是什麼?您是否使用瀏覽器開發者工具? (F12) – Snixtor