ASP.NET MVC how can I return an error from a file download action without leaving the current page?

雨燕双飞 提交于 2019-12-08 07:51:08

问题


I am calling a file download action from javascript:

$elem.click(function() { 
    window.location.href = 'MyController/MyFileDownloadAction';
});

The controller returns a file:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyFileDownloadAction()
{
    /* do some processing, generate an in-memory file... */

    return File(myFileStream, "text/plain", myFileName);
}

This action has a pretty high likelyhood of throwing an exception (or at least not being able to return the file).

Due to the nature of the application (which contains a lot of dynamic content), I can't really redirect to an error page in this situation. The current page needs to stay open somehow.

So I'm ideally looking for something like a javascript pop-up, but afaik this isn't going to be possible since I don't know any way to return a javacript instruction in a non-ajaxed controller call. If I display an error page I need to force it to open in a new window some how. Is there any possible solution to this problem?


回答1:


I don't believe it's possible to do what you want. As soon as you do a "window.location.href = 'somelocation'", you are instructing the current browser window to request 'somelocation' and render the result, whatever it may be. Therefore, you need to output whatever error information in the result to that request.

Now, there is no reason that you would need to redirect to an error page. You could return a ViewResult containing the error message or any other kind of result.



来源:https://stackoverflow.com/questions/3229280/asp-net-mvc-how-can-i-return-an-error-from-a-file-download-action-without-leavin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!