<Professional ASP.NET MVC 5> - Note 02

50 篇文章 0 订阅
17 篇文章 0 订阅

CHAPTER 8 Ajax


Respond.js: adds support for newer browser standards to older browsers. Like min-width and max-width CSS3 media query support for Internet Explorer 6–8.

Modernizr.js: modernizing older browsers. For example, one important job of Modernizr is to enable the new HTML 5 elements (such as header, nav, and menu) on browsers that don't natively support HTML 5 elements (like Internet Explorer 6).


The files with "unobtrusive" in the name are those written by Microsoft. The unobtrusive scripts integrate with jQuery and the MVC framework to provide the unobtrusive JavaScript features. You'll need to use these files if you want to use Ajax features of the ASP.NET MVC framework.


Script Optimizations

  • Moving all your script tags to the bottom of a page (just before the closing body tag) yields a better experience for the user.
  • Minimize the number of script tags you send to a client.
  • Tools like YSlow, can help you make the right decisions.


ASP.NET MVC 5 has the ability to bundle scripts, so you can combine multiple script files into a single download for the client. MVC 5 can also minify scripts on the fly to produce a smaller download.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css","~/Content/site.css"));


A script bundle is a combination of a virtual path (such as ~/bundles/jquery, which is the first parameter to the ScriptBundle constructor) and a list of files to include in the bundle. The  virtual path is an identifier you'll use later when you output the bundle in a view. The list of fi les in a bundle can be specified using one or more calls to the Include method of a bundle, and in the call to include you can specify a specific filename or a filename with a wildcard to specify multiple files at once.


The following code outputs the jQuery bundle and the default application style sheet:

@Scripts.Render("~/bundles/jquery")


When the application is running in debug mode (specifically, the debug flag is set to true in the compilation section of web.config), the script and style helpers render a script tag for each individual file registered in the bundle. When the application is running in release mode, the helpers combine all the files in a bundle into a single download and place a single link or script element in the output.

In release mode, the helpers also minify files by default to reduce the download size.





CHAPTER 9 Routing


Unless both parameters have a default value, a potential ambiguity exists, so Routing will ignore the default value on the {action} parameter.

When you specify a default value for one parameter, make sure you also specify default values for any parameters following it, or your default value will largely be ignored. Given the URL pattern {controller}/{action}/{id}, providing a default value for {action} without specifying a default for {id} is effectively the same as not having a default value for {action}.

Constraints allow you to apply a regular expression to a path segment to restrict whether the route will match the request.

You put your new route before the default simple route because routes are evaluated in order.


Namespaces are used to narrow down the set of controllers that are considered when matching a route. When a route has a namespace defined, only controllers that exist within that namespace are valid as a match. But in the case of a route that doesn't have a namespace defined, all controllers are valid.

If you have two controllers with the same name, one within an area and one in the root of your application, you might run into an exception. You can specify a set of namespaces to use for locating controller classes for a particular route. The following code shows how to do that using a traditional route:

routes.MapRoute(
	"Default",
	"{controller}/{action}/{id}",
	new { controller = "Home", action = "Index", id = "" },
	new [] { "AreasDemoWeb.Controllers" }
);


Catch-All Parameter

A catch-all parameter allows for a route to match part of a URL with an arbitrary number of segments. The value put in the parameter is the rest of the URL path

public static void RegisterRoutes(RouteCollection routes)
{
	routes.MapRoute("catchallroute", "query/{query-name}/{*extrastuff}");
}


A route URL may have multiple parameters per segment. For example, all the following are valid route URLs:

➤ {title}-{artist}
➤ Album{title}and{artist}
➤ {filename}.{ext}


To avoid ambiguity, parameters cannot be adjacent. For example, the following are invalid:

➤ {title}{artist}
➤ Download{filename}{ext}


When a request comes in, Routing matches literals in the route URL exactly. Route parameters are matched greedily, which has the same connotations as it does with regular expressions. In other words, the route tries to match as much text as possible with each route parameter.

{filename}.{ext}/Foo.xml.aspxfilename="Foo.xml" ext="aspx"
My{location}-{sublocation}/MyHouse-dwellinglocation="House" sublocation="dwelling"
{foo}xyz{bar}/xyzxyzxyzblahfoo="xyzxyz" bar="blah"

One way to ensure that Routing ignores such requests is to use the StopRoutingHandler.

public static void RegisterRoutes(RouteCollection routes)
{
	routes.Add(
		new Route
		(
			"{resource}.axd/{*pathInfo}", new StopRoutingHandler()
		)
	);
	routes.Add(
		new Route
		(
			"reports/{year}/{month}", new SomeRouteHandler()
		)
	);
}


There's an even easier way to tell Routing to ignore a route:

public static void RegisterRoutes(RouteCollection routes)
{
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
	routes.MapRoute("report-route", "reports/{year}/{month}");
}


To use the Route Debugger, install RouteDebugger via the Package Manager Console window in Visual Studio.


It adds a setting to the appSettings section of web.config used to turn Route Debugger on or off:

<add key="RouteDebugger:Enabled" value="true" />


Ambient Route Values

In some scenarios, URL generation makes use of values that were not explicitly supplied to the GetVirtualPath method by the caller.

In Simple Case, the Routing system uses the ambient route data values for the controller and action when performing the route lookup.

Overflow Parameters

Overflow parameters are route values used in URL generation that are not specified in the route's definition.

Note that ambient values are never used as overflow parameters.

Overflow parameters used in route generation are appended to the generated URL as query string parameters.

We've specified more parameters than needed those extra parameters are appended as query string parameters.
The important thing to note is that Routing is not looking for an exact match when determining which route is a match.

It's looking for a sufficient match.

As long as the specified parameters meet the route's expectations, it doesn't matter if extra parameters are specified.









CHAPTER 11 ASP.NET Web API


Web API controllers almost always return a raw object value (or sequence of values) or an action result. When an action returns a raw object, Web API will automatically convert it into a structured response in the desired format (such as JSON or XML) using a feature of Web API called Content Negotiation.

How do you support returning some different representation for errors? Web API allows developers to throw HttpResponseException from their actions to indicate that they are returning an HttpResponseMessage rather than successful object data.

Web API 2 introduced a better solution to this problem: the new action result classes. To return action results, Web API controller actions use a return value type of IHttpActionResult.

A final note about action return values: If your action is asynchronous in nature you can modify the signature of your action return value to be Task<T> and use the async and await features in .NET 4.5 to seamlessly convert your sequential code into asynchronous code.


The configuration class includes access to the following items:
➤ Routes
➤ Filters to run for all requests
➤ Parameter binding rules
➤ The default formatters used for reading and writing body content
➤ The default services used by Web API
➤ A user-provided dependency resolver for DI on services and controllers
➤ HTTP message handlers
➤ A flag for whether to include error details such as stack traces
➤ A Properties bag that can hold user-defined values


Web-hosted Web API supports only a single server and single configuration file, and the developer is not responsible for creating these, only for configuring them as appropriate.

The most significant difference between the default MVC route and the default Web API route is the lack of the {action} token in the latter. Web API actions are dispatched to by default based on the HTTP verb that the request used. You can override this mapping by using the {action} matching token in the route (or by adding an action value to the default values for the route).

When you write an action method signature and include parameters, complex types come from "the body," which really means that formatters are responsible for generating them; simple types, on the other hand, come from "not the body," which means that model binders are responsible for generating them. For body content being sent, you use formatters to decode the data.

Parameter Binding. Web API uses parameter binders to determine how to provide values for individual parameters. You can use attributes to influence that decision, but the default logic uses the simple type versus complex type logic when there are no overrides applied to influence the binding decision.

ModelBinderAttribute:
FromUriAttribute:
FromBodyAttribute:


Model binding in Web API works mostly the same way as MVC. You will find built-in model binders for arrays, collections, dictionaries, simple types, and yes, even complex types (though you would need to use [ModelBinder] to get them to run, obviously).


Formatters are responsible for both consuming and producing body content. You can think of them in much the same way you might think of serializers in .NET: classes that are responsible for encoding and decoding custom complex types into and out of the stream of bytes, which is the body content.


Built into Web API you will fi nd three formatters, one which:
➤ Encodes and decodes JSON (using Json.NET)
➤ Encodes and decodes XML (using either DataContractSerializer or XmlSerializer)
➤ Decodes form URL encoded from data in the body from a browser form post.


Developers can acquire the IApiExplorer service from HttpConfiguration.Services and use it to programmatically explore the APIs exposed by the service.


TRACING THE APPLICATION

Web API enables a very rich automatic tracing ecosystem that is turned off by default.

The central part of tracing is the ITraceWriter service. Web API does not ship with any implementations of this service because it is anticipated that developers will likely already have their own favorite tracing system (such as ETW, log4net, ELMAH, or many others).

On startup Web API checks whether an implementation of ITraceWriter is available in the service list, and if so, automatically begins tracing all requests. The developer must choose how best to store and browse this trace information—typically, by using the configuration options provided by their chosen logging system.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值