Archive for the ‘web api’ Category

Other publish

Code:
    ///In filters register:
    // This method allows the client to override their browser's HTTP Accept header by putting a value in the querystring.
    //...
    GlobalConfiguration.Configuration.Filters.Add(new FormattingOverrideFilterAttribute(formatPreferenceOverride: "application/json", clearOtherPreferredMediaTypes: true));
    //...
///...

public class FormattingOverrideFilterAttribute : ActionFilterAttribute{
    /// <summary>
    /// Allows overriding the Accept header by querystring or server preference.
    /// </summary>
    /// <param name="formatPreferenceOverride">If defined, this mime type will be injected into the Accept header of every request.</param>
    /// <param name="newQuality">Optional, The quality setting for this media type. Should be between 1 and 0.</param>
    /// <param name="clearOtherPreferredMediaTypes">If true, will remove all other media types from the Accept header.</param>
    public FormattingOverrideFilterAttribute(string formatPreferenceOverride = null, double? newQuality = null, bool clearOtherPreferredMediaTypes = false) : base() {
        NewQualityValue = newQuality;
        FormatPreferenceOverride = formatPreferenceOverride;
        ClearOtherPreferredMediaTypes = clearOtherPreferredMediaTypes;
    }

    public double? NewQualityValue { get; set; }
    public string FormatPreferenceOverride { get; set; }
    public bool ClearOtherPreferredMediaTypes { get; set; }

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
        var qs = actionContext.Request.RequestUri.ParseQueryString();

        var requestedMediaType = (qs["f"] ?? qs["format"] ?? FormatPreferenceOverride ?? String.Empty).ToLower();

        switch (requestedMediaType) {
            case "xml":
            case "x":
                requestedMediaType = "application/xml";
                break;
            case "j":
            case "js":
            case "json":
                requestedMediaType = "application/json";
                break;
        }

        if (String.IsNullOrEmpty(requestedMediaType))
            return; // No action is necessary because no override was requested.

        var acceptHeaders = actionContext.Request.Headers.Accept;
        MediaTypeWithQualityHeaderValue header = null;

        if (ClearOtherPreferredMediaTypes) {
            var newAcceptHeaders = acceptHeaders.Where(h => h.MediaType == requestedMediaType || h.MediaType == "*/*").ToList();
            acceptHeaders.Clear();
            newAcceptHeaders.ForEach(acceptHeaders.Add);
        }

        header = acceptHeaders.FirstOrDefault(h => h.MediaType == requestedMediaType);
        if (header == null) {
            header = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(requestedMediaType);
            acceptHeaders.Add(header);
        }

        System.Diagnostics.Debug.WriteLine("Overidding HttpAccept header for format preference.");
        header.Quality = NewQualityValue;
    }
}

Sources:

Best—> http://weblog.west-wind.com/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

Another…. ->http://weblog.west-wind.com/posts/2012/Mar/09/Removing-the-XML-Formatter-from-ASPNET-Web-API-Applications

Simple, reference that:

 

using Microsoft.AspNet.Identity;

 

After you can see two extensions:

//get User Id
var CurrentUserId = User.Identity.GetUserId()
//get UserName
var CurrentUserName = User.Identity.GetUserName()

Enjoy it!

SignalR

Posted: October 23, 2013 in developing, javascript, mvc, signalR, web api
Tags: ,

About

ASP.NET SignalR is a new library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets, and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

Links:

  1. Getting Started with ASP.NET SignalR 2.0 (8 Tutorials)

    What is SignalR 2.0 and how to get started adding real-time functionality to a web application.

  2. Hubs API (6 Tutorials)

    This chapter contains information on using Hubs, the higher-level of the two communication paradigms used by SignalR

  3. Security (3 Tutorials)

    This chapter contains information on using authorization in SignalR.

  4. Performance and Scaling (5 Tutorials)

    This chapter contains information on performance and scaling in SignalR.

  5. Troubleshooting and Debugging (1 Tutorials)

    This chapter contains information on finding and fixing issues with SignalR applications.

  6. Extensibility (1 Tutorials)

    Extensibility and dependency injection n SignalR.

 

Source: http://www.asp.net/signalr

Free Microsoft Training…

Courses by Topics

  • C# / XAML
  • HTML5
  • Virtualization
  • Managing Desktop & Devices
  • Server Infrastructure
  • Management & Security
  • Private Cloud
  • Business Intelligence
  • Collaboration
  • Licensing
  • App Development

Courses by Products

  • Windows
  • Windows Server
  • Visual Studio
  • System Center
  • SQL Server
  • Windows Azure
  • Office

Link: http://www.microsoftvirtualacademy.com/

This tutorial shows how to support CRUD operations in an HTTP service using ASP.NET Web API.

CRUD stands for “Create, Read, Update, and Delete,” which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs.

In this tutorial, you will build a very simple web API to manage a list of products. Each product will contain a name, price, and category (such as “toys” or “hardware”), plus a product ID.

Download the completed project.

The products API will expose following methods.

Action HTTP method Relative URI
Get a list of all products GET /api/products
Get a product by ID GET /api/products/id
Get a product by category GET /api/products?category=category
Create a new product POST /api/products
Update a product PUT /api/products/id
Delete a product DELETE /api/products/id

Notice that some of the URIs include the product ID in path. For example, to get the product whose ID is 28, the client sends a GET request for http://hostname/api/products/28.

Resources

The products API defines URIs for two resource types:

Resource URI
The list of all the products. /api/products
An individual product. /api/products/id

Methods

The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows:

  • GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
  • PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs. For this tutorial, the API will not support creation through PUT.
  • POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
  • DELETE deletes a resource at a specified URI.

Note: The PUT method replaces the entire product entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred. This tutorial does not implement PATCH.

Create a New Web API Project

Start by running Visual Studio and select New Project from the Start page. Or, from the File menu, select Newand then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project “ProductStore” and click OK.

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

Adding a Model

model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client. (more…)