What clever things have you done with an ASP.NET MVC Action method

半世苍凉 提交于 2019-11-28 15:23:43

Does a HTTP 301 Redirect count as clever?

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;
    }
}

View result with email confirmation:

public abstract class ViewResultWithConfirmationEmail: ViewResult
{
    protected readonly string toAddress;

    protected ViewResultWithConfirmationEmail(string toAddress)
    {
        this.toAddress = toAddress;
    }

    protected abstract MailMessage CreateEmail(ControllerContext context);

    protected override void ExecuteResult(ControllerContext context)
    {
        MailMessage message = CreateEmail(context);
        var smtpClient = new SmtpClient();
        smtpClient.Send(message);

        base.ExecuteResult(context);
    }
}

Some of the implementation details have been omitted here, but I could use this to implement a RegistrationSuccessResult class, for example, that would send an email message with the appropriate text after a successful user registration.

The reason I chose to send the message in a subclassed ViewResult instead of in the action method itself was to make it easier to separate my unit tests.

A partial implementation of less, a css syntax extender

It actually support only constants and what they called mixins, the source are here.

In this post I explained how to use it in mvc (the post is in italian but just look at the source):

you can just look here at the result

Actually, not an "action" method, but a custom controller that implements a route-base RPC implementation. It identifies the contract and method from the route-data and passes the call onto the server-side service implementation. Pretty efficient (and yes, there are valid reasons that I'm not just using WCF or SOAP).

Not sure how many of you are using areas but an XCopy script is pretty necessary when making View changes in an Area. Areas compile into the parent project but only on compile (not on save) so to keep the dev agility, you'll need to run an XCopy.

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