使用ASP.NET MVC Action方法做了哪些聪明的事情

Sim*_*ver 24 .net asp.net-mvc actionmethod

ASP.NET MVC控制器操作方法主要用于处理"业务"操作,但它可以用于更多.

我认为看到人们创造的创造性,有用的东西对他人来说可能是实用的或有用的,这会很有趣.

这是我的贡献:

Javascript文件连接器 - 减少http请求的数量:

    [OutputCache(Duration = 5 * 60, VaryByParam="")]  // DONT USE "None" here *
    public ContentResult RenderJavascript(){

        StringBuilder js = new StringBuilder();
        StringWriter sw = new StringWriter(js);

        // load all my javascript files
        js.AppendLine(File.ReadAllText(Request.MapPath("~/Scripts/jquery.hoverIntent.minified.js")));
        js.AppendLine(File.ReadAllText(Request.MapPath("~/Scripts/jquery.corner.js")));
        js.AppendLine(File.ReadAllText(Request.MapPath("~/Scripts/rollingrazor.js")));

        return new ContentResult()
        {
            Content = js.ToString(),
            ContentType = "application/x-javascript"
        };
    }
Run Code Online (Sandbox Code Playgroud)

映射到它的路线:

  // javascript
  routes.MapRoute(
     "js-route",
     "dynamic/js",
     new { controller = "Application", action = "RenderJavascript" }
  );
Run Code Online (Sandbox Code Playgroud)

请从您的母版页中查看:

    <script type="text/javascript" src="/dynamic/js"></script>
Run Code Online (Sandbox Code Playgroud)

请注意,我已为输出设置了缓存,因此如果您要更改JS并刷新页面,则可能需要禁用缓存!

我需要回来找出如何gzip它.

*您不应该使用VaryByParam ="None",因为这会导致发送Vary标头,这会导致浏览器返回并检查新版本.如果你真的需要更改你的js内容,那么你的用户只需要等待5分钟!

Mic*_*tum 14

HTTP 301重定向是否算聪明?

public class PermanentRedirectResult : ActionResult
{
    public string Url { get; set; }

    public PermanentRedirectResult(string url)
    {
        if (string.IsNullOrEmpty(url))
        {
            throw new ArgumentException("url is null or empty", "url");
        }
        this.Url = url;
    } 

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        context.HttpContext.Response.StatusCode = 301;
        context.HttpContext.Response.RedirectLocation = Url;
    }
}
Run Code Online (Sandbox Code Playgroud)