ASP.net MVC - Check status request
Just wondering if its possible to get the status of a request from another request?
To help provide some context, I want to use ajax to upload some files to the server. When the upload is started I want triggered another ajax request that checks to see how much of the file has been uploaded (or in other words how big was the other request and how far through receiving the request is the server).
I was thinking that I could use a guid or something similar to ensure that I am checking the status of the right request. But how do I check the status of ano开发者_开发问答ther request???
Cheers Anthony
It's definitely possible. There's no built in support for checking the status of another request in ASP.NET MVC as far as I'm aware but it's not hard to implement.
public static UploadStatusHelper {
static Dictionary<string, int> uploads = new Dictionary<string, int>();
static object lockObj = new object();
public static void SetStatus(string key, int bytesComplete) {
lock(lockObj) {
uploads[key] = bytesComplete;
}
}
public static void GetStatus(string key) {
lock(lockObj) {
int bytesComplete = 0;
if(uploads.TryGetValue(key, out bytesComplete) {
return bytesComplete;
}
return 0;
}
}
}
When you've read a chunk of the uploaded file on the server, you would call
UploadStatusHelper.SetStatus(theKey, bytesRead);
Then using using Ajax you can initiate an HTTP POST request periodically to an action which returns the progress, e.g.
[HttpPost]
public ActionResult GetProgress(string key)
int bytesRead = UploadStatusHelper.GetStatus(key);
return Json(new { bytesRead = bytesRead });
}
You'd probably want to extend this helper to store the total length of the file and return a percentage complete, but this is just meant to show you how it could be done.
You'll probably want to look into implementing Asynchronous requests in ASP.NET MVC, or something similar.
精彩评论