ASP. net mvc project practices and asp. netmvc project practices

Source: Internet
Author: User

ASP. net mvc project practices and asp. netmvc project practices

Original article reprinted please indicate the source: @ cosi, http://zeeman.cnblogs.com

At the early stage of. NET development, Microsoft provided a WEB development model called WebForm, which tried to eliminate the gap between Web and desktop and establish a consistent development experience. However, the ideal is very plump, and the reality is very skinny. The Web development method is completely different from the desktop software. Compared with WebForm, the later developed MVC obviously meets the needs of Web developers. The code quality is significantly improved, and the performance is also optimized a lot.

When I was working on the MVC project, I had some habits:

1. encapsulate the frequently used methods in Request and Response as extension methods, such as the method for obtaining logon UserId:

public static AuthMemberInfo GetMember(this HttpRequestBase request){    if (request.IsAuthenticated)    {        HttpCookie authCookie = request.Cookies[FormsAuthentication.FormsCookieName];        FormsAuthenticationTicket Ticket = FormsAuthentication.Decrypt(authCookie.Value);        return JsonConvert.DeserializeObject<AuthMemberInfo>(Ticket.UserData);    }    return null;}

2. Permission verification inherits the AuthorizeAttribute class and implements its own authentication logic:

public override void OnAuthorization(AuthorizationContext filterContext){    var user = filterContext.HttpContext.Request.GetMember();    if (user == null)    {        filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl            + "?returnUrl=" + filterContext.HttpContext.Server.UrlEncode            (filterContext.HttpContext.Request.RawUrl));        return;    }}

In this way, add this Attribute to any Controller or method that requires permission verification.

3. All controllers inherit the custom BaseController to perform unified behavior when necessary, such as logging in OnException.

4. MVC uses the JSON serializer of the framework to compare the disadvantages. In particular, date processing is not in the ISO format, which makes front-end JS troublesome. We can handle the Override Json method in BaseController:

protected override JsonResult Json(object data, string contentType,     Encoding contentEncoding, JsonRequestBehavior behavior){    return new JsonNetResult    {        Data = data,        ContentType = contentType,        ContentEncoding = contentEncoding,        JsonRequestBehavior = behavior    };}

JsonNetResult uses Json.net as the serializer, which is flexible:

public class JsonNetResult : JsonResult{    public override void ExecuteResult(ControllerContext context)    {        if (context == null)            throw new ArgumentNullException("context");        var response = context.HttpContext.Response;        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";        if (ContentEncoding != null)            response.ContentEncoding = ContentEncoding;        if (Data == null)            return;        var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented,            new StringEnumConverter { CamelCaseText = false });        response.Write(serializedObject);    }}

5. After Global. asax detects a Global exception, it is handed over to ErrorController for processing:

Var routeData = new RouteData (); routeData. values. add ("controller", "Error"); routeData. values. add ("action", "ThrowError"); routeData. values. add ("message", "Sorry, an internal error occurred on the server. "); Server. clearError (); // output service exception information IController errorController = new ErrorController (); errorController. execute (new RequestContext (new HttpContextWrapper (this. context), routeData ));

How to Implement aspnet mvc?

The problem is widespread in space. It is recommended that you learn mvc first. If you learn about it, you can look at mvc-related projects or the source code of mvc. Good luck! Think more, practice diligently, do not simply look at and do not practice!

How to create the aspnet mvc Project

Install Visual Studio 2008 + SP1, install Microsoft's asp.net mvc Framework, and find the MVC project in the category of new Web applications.

Asp.net mvc 2
Www.microsoft.com/..8615a9

Asp.net mvc 1
Www.microsoft.com/..03cb4b

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.