ASP .Net MVC应用程序中的自定义Http处理程序

时间:2016-03-20 21:00:18

标签: c# asp.net asp.net-mvc httphandler

出现一个奇怪的问题。虽然它按预期工作但它有点烦人。 我试图使用Custom Http Handler构建一个图像处理程序。所以每当用户请求URL赞

http://localhost:49376/privateimage/dog

狗图像是显示的。如果他选择了一只猫

http://localhost:49376/privateimage/cat

显示cat.jpg。这是我到目前为止所做的事情

public class CustomMVCRouteHandler :IRouteHandler //Register our HttpHandler inside our RouteConfig file
{

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new CustomMVCHandler(requestContext);
    }
}

处理程序看起来像

   public class CustomMVCHandler : IHttpHandler //For this custom HttpHandler we need a RouteHandler which will route our requests
{
    //Create a RequestContext object 
    public RequestContext requestContext{get;set;}

    //Create a parameterized constructor for the class and initialize the requestContext object
    public CustomMVCHandler(RequestContext reqCon)
    {
        requestContext = reqCon;
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string requestedAction = context.Request.Url.Segments[2].ToLower(); // Context object is the bridge connecting your
        var routeValues = context.Request.RequestContext.RouteData.Values;
        if (routeValues.ContainsKey("image") && !string.IsNullOrEmpty(routeValues["image"].ToString()))
        {
            requestContext.HttpContext.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            string xsltPath = Path.Combine(context.Server.MapPath("~/Content/Images"), routeValues["image"].ToString());
            xsltPath = xsltPath + ".jpg";
            context.Response.WriteFile(xsltPath);
            requestContext.HttpContext.Response.End();
        }

        StreamWriter sw = new StreamWriter(@"C:\Education & Jobs\ASP .Net MVC\Logs\Log.txt", true);
        sw.WriteLine("The static file requested is -- " + requestedAction);
        sw.WriteLine("Static file requested at -- " + DateTime.Now.ToString() +" "+ requestedAction);
        sw.Close();
    }

    #endregion
}

Route.config看起来像:

routes.Add("ImageRoute",new Route("privateImage/{image}",new CustomMVCRouteHandler()));

但是现在我遇到的问题有时是在请求Dog图像并且在我们开始输入cat的URL时显示图像,然后完全输入它并按下Enter 处理程序代码是在调试器模式下再次点击,页面刷新与之前的dog.jpg图像。反之亦然。

我不完全确定发生了什么。但这就是我发现的。

enter image description here

这里即使我们刚开始输入

的网址
http://localhost:49376/privateimage/dog

再次点击调试器模式下的代码。

enter image description here

并显示默认主页。

enter image description here

这种延迟的原因是什么?断点是否与它们有关?

0 个答案:

没有答案