我建议一个HttpHandler
。没有页面生命周期(因此速度非常快),代码分离更加清晰,并且具有可重用性。
将一个新项目添加到“通用处理程序”类型的项目中。这将创建一个新的 .ashx 文件。任何实现类的主要方法IHttpHandler
is ProcessRequest
。因此,要使用原始问题中的代码:
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
更改 AJAX 调用中的 url 就可以了。 JavaScript 看起来像这样,其中获取文件处理程序.ashx是您刚刚创建的 IHttpHandler 的名称:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
另一个需要考虑的小问题是,如果您需要从 Handler 代码本身访问 Session 对象,请确保继承自IRequiresSessionState
界面:
public class GetFileHandler : IHttpHandler, IRequiresSessionState