Showing posts with label Web API 2. Show all posts
Showing posts with label Web API 2. Show all posts

Tuesday, April 21, 2015

Paged List for WebAPI

One of my favorite quotes is "there is nothing as embarrassing as yesterday's code." I blogged about a paged list class a while back, but I no longer like that implementation...so here is a new one that includes WebAPI serialization support!

...but why is this useful?

You can use the simple IPagedList interface to pass paged data around all of your application, and then any object returned from your WebAPI that implements IPagedList will be automatically serialized for you. This allows you to create very consistent APIs that support paging.

IPagedList Interfaces

public interface IPagedList
{
 int PageIndex { get; }
 
 int PageSize { get; }
 
 int TotalCount { get; }
 
 IList List { get; }
}
 
public interface IPagedList<T> : IPagedList
{
 new IList<T> List { get; }
}

Friday, November 28, 2014

Web API - Return Correct Status Codes for Exceptions

Returning the appropriate HTTP Response Codes back from your web server is a very important best practice. Fortunately for .NET developers, Web API makes it very easy to use Exception Filters to return the appropriate response codes from your exceptions.

By implementing a custom ExceptionFilterAttribute you can generically create and return HttpResponseMessages for unhandled exceptions based on type. This is great in that you do not have to wrap all of your controller actions in try catch blocks to handle exceptions from other application layers.

Sample Controller

public class ValuesController : ApiController
{
 public string Get(int id)
 {
 switch (id)
 {
 case 1:
 throw new KeyNotFoundException("Hello World");
 
 case 2:
 throw new ArgumentException("Goodnight Moon");
 
 default:
 return "value";
 }
 }
}

Saturday, November 22, 2014

Web API - Bad Request when Model State is Invalid

When you using Web API, would you like to always return a 400 (bad request) response whenever the model state is invalid? It is easy, just add the following filter attribute to your global list:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
 AllowMultiple = false, 
 Inherited = true)]
public class InvalidModelStateFilterAttribute : ActionFilterAttribute
{
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
 if (!actionContext.ModelState.IsValid)
 {
 actionContext.Response = actionContext.Request.CreateErrorResponse(
 HttpStatusCode.BadRequest, 
 actionContext.ModelState);
 }
 }
}

Enjoy,
Tom

Sunday, August 3, 2014

Basic and Digest mixed authentication with WebAPI

In my last post I talked about using both Basic and Digest authentication with WebAPI, but not at the same time. So what do you do when you want to used mixed authentication with both?

In principal you can support both Basic and Digest authentication at the same time, but your server has to issue the 401 challenge with Digest. This is because basic requires no token or server information to authenticate, where as digest requires a nonce from the server.

I have updated Rick's Basic authentication and Badri's Digest authentication implementation to work together as a pair of AuthorizationFilterAttributes. Here is the source:

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
 config.Filters.Add(new BasicAuthorizationFilterAttribute(false));
 config.Filters.Add(new DigestAuthorizationFilterAttribute());
 config.MapHttpAttributeRoutes();
 config.Routes.MapHttpRoute(
 "DefaultApi",
 "{controller}/{id}",
 new { controller = "data", id = RouteParameter.Optional }
 );
 }
}

Enjoy,
Tom

Thursday, July 31, 2014

WebAPI and Chrome Authentication Types

Google Chrome supports four HTTP authentication types:

  1. Basic
  2. Digest
  3. NTLM
  4. Negotiate

ASP.NET WebAPI has AuthorizationFilterAttributes which can be used to implement both Authentication and Authorization for your APIs. If you want to use Basic or Digest authentication, there are already several open source implementations available to help you out!

Do you need to used mixed authentication and support both Basic and Digest?
If so, be sure to check out my next blog post...

Enjoy,
Tom

Friday, July 5, 2013

Microsoft Build 2013 for Web Developers

Build 2013 was a whole lot of fun!

The big reveals at Build 2013 was Windows 8.1 and Visual Studio 2013. Admittedly Microsoft's big focus was on the Windows 8 store, but that does not mean that they are not delivering great tools for the fastest growing development environment in the world: the web!

Before we discuss web development, let's first take a moment to talk about Windows.

Windows 8.1 actually looks really good! Like all Microsoft products, the first major patch manages to iron out most of the kinks. The new UI updates and inclusion of the start button make the modern UI and desktop seem much less polarizing. Additionally, I am very optimistic about seeing Windows 8 applications come to PC, table, and phone. Microsoft has always had great potential for creating a homogeneous ecosystem consumer devices, and I am finally getting excited about the product line up that they are delivering.

New Editors in Visual Studio 2013

The Visual Studio Team has completely rewritten the HTML and JavaScript editors from scratch in Visual Studio 2013. This is great news; not only are the new editors faster, more responsive, and have much better intellisense, but they also come with a set of fun new features.

  • The overall Razor experience has been greatly improved.
  • Intellisense now include expandable groups to keep drop downs from getting cluttered.
  • CSS intellisense now displays browser compatibility for each rule.
  • New shift alt keys allows you to select content from tree structures.

Microsoft has yet to announce how they will charge for Visual Studio 2013. Will it be a stand alone install, will it be full price, we just do not know yet. Personally, I would love to see Visual Studio more to incremental update system, but obviously there would be lot of technical limitation to doing so...but hey, a dev can dream!

HTML Editing Features in Visual Studio 2013 Preview

Browser Link

Visual Studio 2013 comes with a built in feature called Browser Link. This is where Visual Studio opens a socket connection directly to your browsers (yes, plural) via SignalR that allows your IDE to send commands directly to the browser itself. The most basic use of this a simple refresh button that allows you to refresh all your browser windows on command.

The potential of this feature is fun to think about! Right now the Visual Studio team is intentionally keeping their default feature set for Browser link very simple, but also open source; as they want to see what us developers come up with. Remember that this is a two way channel of communication between the browser and the IDE, so sending error messages back to Visual Studio is just the first thing that comes to my mind.

A cool demo that they showed us at Build was keeping multiple browser windows in sync, this included form elements and page navigation. The cool part was that these browsers included Chrome, Firefox, and IE running on a virtualized windows phone. It was a very compelling demo!

Browser Link feature in Visual Studio Preview 2013

Web API 2.0

Web API was a great addition to Microsoft's web development library, and 2.0 looks like a great incrimental update to that framework. Forgive me if it seems that I do not have much to say about Web API 2, it just seems like a very simple but very welcome update to the framework; but don't let that fool you, I am stoked!

  • Attribute based routing.
  • Integrated OAuth 2 authentication.
  • OWIN Web hosting (run your APIs outside of IIS)
  • Cross-Origin Resource Sharing

ASP.NET Web API 2

TypeScript 0.9

I am SO excited about TypeScript!

TypeScript is a development language that is a super set of JavaScript. It adds type checking, interfaces, and inheritance to JavaScript. The idea is that you develop in TypeScript and then compile that language down to JavaScript for deployment on the web. The key here is that TypeScript is a super set of JavaScript, so all JavaScript code is already valid TypeScript, making it very easy for you to start your migration from language to the other.

There are essentially two ways that you could choose to use TypeScript:

  1. Use TypeScript for simple type checking and enhanced refactoring.

This is probably the more ideal use of TypeScript, or at least the simplest. The idea being that you can constrain your function parameters by type and interface, and make use of TypeScripts more strick declarations for easier refactoring. You would also get significantly improved intellisense both for your code and other frameworks, as a very active open source community has been creating interface wrappers for everything from JQuery to Knockout.

  1. Go full monty, and make your JavaScript completely Object Oriented.

Using TypeScript would allow you to define and extend both classes and interfaces, just as you would a language like C#. This opens the possibility for polymorphism, dependency injection, mocking, testing, the whole object oriented play book. While this does go against many principals of a very functional programming language like JavaScript, it also enables a lot of best practices that help simplify large scale application development.

...how far you want to go using TypeScript is up to you, but regardless of which side of the fence you are on, I definitely feel that TypeScript is worth looking into!

www.typescriptlang.org

Shout it

The future looks bright,
Tom

Subscribe to: Posts (Atom)

AltStyle によって変換されたページ (->オリジナル) /