ASP.NET 4.0 Hosting & ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4.5 Hosting, ASP.NET 4.0 Hosting and .NET 4.5 Framework and its Capabilities

Unlimited Domains Windows Hosting with ASPHostCentral.com

clock September 27, 2011 08:52 by author Administrator

 

A lot web hosting service providers will only allow you to host a single domain name on a single account. This works fine if you plan on having one website only. But later on when you need to setup additional websites, you will need to purchase a separate web hosting account for each of those additional websites. So for example, if you have 10 websites, you will need to pay for 10 web hosting accounts.

What's UNLIMITED Domain Hosting?

Unlimited Domain Hosting allows you to host unlimited number of domain names, or websites, under a single web hosting account. A hosting plan that allows unlimited Domain Hosting will definitely save you money since you can sign up for an account with one company and manage your websites from a central location.

Aside from saving you money, it also allows you to save time. Since all the domains would be hosted on the same hosting account, you can administer each domain simultaneously through the same control panel.

How Do I Take Advantage of Unlimited Domain Hosting?

The best way to get the most out of Unlimited Domain Hosting is to use an "unlimited" web hosting account. With ASPHostCentral.com, you can host any number of domains/websites under one single account and you can start from as low as $4.49/month only!

 



ASP.NET 4.0 Hosting :: SOLVING an error message: “Unrecognized attribute targetFramework”

clock September 22, 2011 07:32 by author Administrator

I recently upgraded from Visual Web Developer 2008 to Visual Web Developer 2010 and have run into an issue, I started seeing a configuration error. In two cases I had been working on web applications in Visual Web developer 2010.


Case 1 appeared after I had opened an existing application and when prompted, do I want to configure the site for use with ASP.NET 4.0, I must have said yes.

Case 2 came when I created a new application and my system is setup to use Framework ASP.NET 4.0

In both situations I got the following error <compilation debug="true" targetFramework="4.0" /> pointing to my web.config file. I like working in Visual Web Developer 2010, but my hosting server is not yet setup for .Net Framework 4.0, so I needed to find out how to down-grade from 4.0 to 3.5 framework.



The following is what I did to change the target Framework from ASP.NET 4.0 to ASP.NET 3.5.

1) Ensure IIS and the ASP.NET properties are configured for Framework 2.0. Note: Framework 3.5 will not show up in the list of installed options due to the fact that framework 3.5 is an extension of 2.0 and not a stand alone release


 2) Configure you web application to use target Framework 4.0 by right clicking your website in the solution explorer >> Property Pages >> Build >> Change "Target Framework" to .NET Framework 3.5.

T



ASP.NET 4 Hosting :: The Difference between Response.Redirect and Response.RedirectPermanent

clock September 20, 2011 07:46 by author Administrator

In ASP.NET 4.0 there are new features that enable developer to make SEO friendly websites very easily. And if you google out, you will find plenty of article which explain this feature. But I am more interested in Response.RedirectPermanent. As the name suggest it is used to redirect permanently moved resources to new location. And most of all articles on the net just explain this with some example. But how can we visualize that whether resource is redirected permanently or not. So here is the answer for that. I have used FireBug to examine the same


Whenever we redirect with Response.Redirect, we can see following activity in FireBug console



As we can see that page which issues Response.Redirect its response status code 302(Found) which means requested url(default.aspx) is found but it is temporarily moved to about.aspx. More information on HTTP status code can be found here.

Now whenever we redirect with Response.RedirectPermanent, we can see following activity in FireBug console



As we can see that page which issues Response.RedirectPermanent its response status code 301(Moved Permanently) which means requested url(default.aspx) is moved Permanently to about.aspx. 301 status code is used by search engine crawler to update search index to new moved information.

I hope information provided here would be more helpful to distinguish between Response.Redirect and Response.RedirectPermanent



.NET 4.5 Hosting :: .NET 4.5 Framework Developer Preview

clock September 19, 2011 11:03 by author Administrator

 

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

This topic contains information about key features and improvements in the .NET Framework 4.5 Developer Preview. This topic does not provide comprehensive information and is subject to change.

New features and improvements are described in the following sections:

- .NET for Metro style apps
- Core New Features and Improvements
- Web
- Networking
- Windows Presentation Foundation (WPF)
- Windows Communication Foundation (WCF)
- Windows Workflow Foundation (WF)

.NET for Metro style apps

Metro style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows using C# or Visual Basic. This subset is called .NET APIs for Metro style apps.

Core New Features and Improvements

The following features and improvements were added to the common language runtime and to .NET Framework classes:

- Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
- Ability to define the culture for an application domain.
- Console support for Unicode (UTF-16) encoding.
- Support for versioning of cultural string ordering and comparison data.
- Better performance when retrieving resources.
- Zip compression improvements to reduce the size of a compressed file.
- Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

Managed Extensibility Framework (MEF)

The Managed Extensibility Framework (MEF) provides the following new features:
- Support for generic types.
- Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
- Multiple scopes.

Asynchronous File Operations

In the .NET Framework 4.5 Developer Preview, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations. To use this new model, use the asynchronous methods in the I/O classes.

Web

ASP.NET 4.5 Developer Preview includes the following new features:

- Support for new HTML5 form types.
- Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
- Support for unobtrusive JavaScript in client-side validation scripts.
- Improved handling of client script through bundling and minification for improved page performance.
- Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
- Support for WebSockets protocol.
- Support for reading and writing HTTP requests and responses asynchronously.
- Support for asynchronous modules and handlers.
- Support for content distribution network (CDN) fallback in the ScriptManager control.

Networking

The .NET Framework 4.5 Developer Preview provides a new programming interface for HTTP applications. For more information, see the new System.Net.Http and System.Net.Http.Headers namespaces.

Also, the following networking improvements are included in the System.Net, System.Net.Mail, and related namespaces:

- Improved internationalization and IPv6 support.
- RFC-compliant URI support.
- Support for Internationalized Domain Name (IDN) parsing.
- Support for Email Address Internationalization (EAI).

Windows Presentation Foundation (WPF)

In the .NET Framework 4.5 Developer Preview, Windows Presentation Foundation (WPF) contains changes and improvements in the following areas:

- The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
- The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
- New features for the VirtualizingPanel and Dispatcher classes.
- Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
- Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface, and retrieval of data binding information from a binding expression.
- Repositioning of data as the values change (live shaping).
- Better integration between WPF and Win32 user interface components.
- Ability to check whether the data context for an item container is disconnected.
- Ability to set the amount of time that should elapse between property changes and data source updates.
- Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

Windows Communication Foundation (WCF)

In the .NET Framework 4.5 Developer Preview, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

- Simplification of generated configuration files.
- Support for contract-first development.
- Ability to configure ASP.NET compatibility mode more easily.
- Changes in default transport property values to reduce the likelihood that you will have to set them.
- Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
- Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
- New asynchronous streaming support.
- New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
- Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
- Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
- Support for configuring services in code.
- XML Editor tooltips.
- ChannelFactory caching support.
- Binary encoder compression support.

Windows Workflow Foundation (WF)

Several new features have been added to Windows Workflow Foundation (WF) in the .NET Framework 4.5 Developer Preview. These new features include:

- Ability to create state machine workflows.
- Enhanced Workflow Designer features such as the following:
    - Enhanced workflow search capabilities in Visual Studio, including Quick Find and Find in Files.
    - Ability to automatically create a Sequence activity when a second child activity is added to a container activity, and to include both activities in the Sequence activity.
    - Panning support, which enables the visible portion of a workflow to be changed without using the scroll bars.
    - A new Document Outline view that shows the components of a workflow in a tree-style outline view and lets you select a component in the Document Outline view.
    - Ability to add annotations to activities.
    - Ability to define and consume activity delegates by using the workflow designer.
    - Auto-connect and auto-insert for activities and transitions in state machine and flowchart workflows.
- Storage of the view state information for a workflow in a single element in the XAML file, so you can easily locate and edit the view state information.
- A NoPersistScope container activity to prevent child activities from persisting.
- Support for C# expressions:
    - Workflow projects that use Visual Basic will use Visual Basic expressions, and C# workflow projects will use C# expressions.
    - C# workflow projects that were created in Visual Studio 2010 and that have Visual Basic expressions are compatible with C# workflow projects that use C# expressions.
- Versioning enhancements:
    - The new WorkflowIdentity class, which provides a mapping between a persisted workflow instance and its workflow definition.
    - Side-by-side execution of multiple workflow versions in the same host, including WorkflowServiceHost.
    - In Dynamic Update, the ability to modify the definition of a persisted workflow instance.
- Contract-first workflow service development, which provides support for automatically generating activities to match an existing service contract


This article is sourced from http://msdn.microsoft.com/en-us/library/ms171868(v=VS.110).aspx as it is correct as per 19th Sept 2011.

 



Silverlight (and WPF) Hosting: How to make items stretch horizontally in a ListBox

clock September 16, 2011 07:46 by author Administrator

 

Sometimes we need to use controls like TextBox, TextBlock etc (that set their width automatically depending on content) in a ListBox’s ItemTemplate. If we need to draw Borders or assign Background colors to each such controls then we may end up having non-equal rows. Here’s a sample markup:


 

Here’s the output for the above XAML:

 

A quick thought would be to assign HorizontalContentAlignment property to Stretch for the TextBox but this wont work. We need to specify this property for the ListBoxItem that encapsulates our DataTemplate. Here’s a quick syntax for doing this using a style:

And here’s the output:

This should be fine in most case but sometimes we also need to wrap the text as highlighted using red arrows in the above image. Now setting TextWrapping property will have no effect as the TextBox thinks it can take all the horizontal space. This can be solved by disabling the horizontal scroll bar for the ListBox:

Here’s the final output:
    

 



ASP.NET Hosting :: Things to AVOID in JSON serialization

clock September 13, 2011 06:59 by author Administrator

If you’ve spent much time working with the .NET platform, ASP.NET’s simple, convention-based approach to exposing JSON endpoints seems just about too good to be true. After years of fiddling with manual settings in XML configuration files, it’s understandable to assume that working with JSON in ASP.NET would require a similar rigmarole, yet it does not.

Unfortunately, this unexpected ease-of-use isn’t obvious if you don’t already know about it, which has led some developers to build needlessly complicated solutions to problems that don’t actually exist. In this post, I want to point out a few ways not to approach JSON in ASP.NET and then show you a couple examples of leveraging the frame work to do it “right”.

A couple examples of what NOT to do

To show you exactly what I’m talking about, let’s start by looking at a few concrete examples of ways that you should not handle sending and receiving JSON in your ASP.NET services.

For all the examples, we’re going to be trying to send and/or receive instances of this Person class:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Once you progress beyond simple scalar types, sending objects (and collections of them) back and forth is a pretty logical next step, and that’s also the point where this manual serialization trouble seems to begin. So, working with this simple Person class should serve as a realistic example, without being overly complex.

Manual serialization, using JavaScriptSerializer

The most common variant of this mistake that I’ve seen is using JavaScriptSerializer to manually build a JSON string and then returning that string as the result of a service method. For example, if you didn’t know better, you might do this to return an instance of the Person class:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public string GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    // Results in {"FirstName":"Dave","LastName":"Ward"}
    string json = jss.Serialize<Person>(dave);
 
    return json;
  }
}

This may look sensible enough on the surface. After all, the json variable does end up containing a nicely serialized JSON string, which seems to be what we want. However, you should not do this.

What actually happens

Part of the beauty of using ASP.NET’s JSON-enabled services is that you rarely have to think much about the translation between JSON on the client-side and .NET objects on the server-side. When requested with the proper incantations, ASP.NET automatically JSON serializes your service methods’ responses, even if their result is an object or collection of objects.

Unfortunately, that automatic translation also makes it easy to end up with doubly-serialized responses if you aren’t aware that ASP.NET is already handling the serialization for you, which is exactly what would happen in the preceding example. The end result is that the Person object is serialized twice before it gets back to the browser – once as part of the method’s imperative code and then a second time by convention.

In other words, it’s understandable to expect the previous code example would return this response:

{"FirstName":"Dave","LastName":"Ward"}

But, what it actually returns is this:

// All the quotes in the manually generated JSON must be escaped in 
//  the second pass, hence all the backslashes.
{"d":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

What a mess. That’s probably not what you had in mind, is it?

Using DataContractJsonSerializer or Json.NET is no better

This may seem obvious, but I want to point out that using a different manual serialization tool, like WCF’s DataContractJsonSerializer or Json.NET, in place of JavaScriptSerializer above does not remedy the underlying problem. I only mention it because I’ve seen those variations of the mistake floating around too.

If anything, in the case of DataContractJsonSerializer, it’s even worse. DCJS’ handling of Dictionary collections and Enums makes life unnecessarily tedious at times, and the code to manually invoke it is even more verbose than that for JavaScriptSerializer.

The impact this mistake has on the client-side

If it weren’t bad enough to add extra computational overhead on the server-side, cruft up the response with escaping backslashes, and increase the size of the JSON payload over the wire, this mistake carries a penalty on the client-side too.

Most JavaScript frameworks automatically deserialize JSON responses, but (rightfully) only expect one level of JSON serialization. That means that the standard functionality provided by most libraries will only unwrap one level of the doubly serialized stack of JSON produced by the previous example.

So, even after the response comes back and your framework has deserialized it once, you’ll still need to deserialize it a second time to finally extract a usable JavaScript object if you’ve made the mistake of manually serializing. For example, this is code you might see to mitigate that in jQuery:

$.ajax({
  type: 'POST',
  dataType: 'json',
  contentType: 'application/json',
  url: 'PersonService.asmx/GetDave',
  data: '{}',
  success: function(response) {
    // At this point, response is a *string* containing the
    //  manually generated JSON, and must be deserialized again.
 
    var person;
 
    // This is a very common way of handling
    //  the second round of JSON deserialization:
    person = eval('(' + response + ')');
 
    // You'll also see this approach, which
    //  uses browser-native JSON handling:
    person = JSON.parse(response);
 
    // Using a framework's built-in helper 
    //  method is another common fix:
    person = $.parseJSON(person);
  }
});

Regardless of which approach is used, if you see code like this running after the framework has already processed a response, it’s a pretty good indication that something is wrong. Not only is this more complicated and verbose than it needs to be, but it adds additional overhead on the client-side for absolutely no valid reason.

Flipping the script (and the JSON)

Redundant JSON serialization on responses is definitely one of the most common variations of this problem I’ve seen, but the inverse of that mistake also seems to be an alluring pitfall. Far too often, I’ve seen service methods that accept a single JSON string as their input parameter and then manually parse several intended inputs from that.

Something like this to accept a Person object form the client-side and save it on the server-side, for example:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(string PersonToSave)
  {
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    Person p = jss.Deserialize<Person>(PersonToSave);
 
    p.Save();
  }
}

Just as ASP.NET automatically JSON serializes responses on its JSON-friendly services, it also expects that the input parameters will be in JSON format and automatically deserializes those on the way in. So, in reverse order, the approach above makes a mistake similar to the ones shown earlier.

To make this work, we’d need to pass in JSON that looks something like this, obfuscating the actually desired input parameters inside a single, doubly-serialized string parameter.

{"PersonToSave":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

Through the convenience of JSON.stringify(), it’s not even terribly hard to stumble onto a process for cobbling that double-JSON structure together on the client-side and making this approach work. I strongly recommend against it though. Even if the double-JSON didn’t carry extra overhead in several aspects, having a single input parameter of type string on this method is misleading. A year from now, will anyone realize what type of parameter that method accepts without looking down into the manual parsing code? Probably not.

Doing it right

Briefly, here are what I suggest as better ways to handle passing our Person object in and out of ASP.NET services.

Returning an object

Returning a .NET object from ASP.NET services is incredibly easy. If you let go and just trust the service to handle JSON translation for you, “it just works”:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public Person GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    // So easy!
    return dave;
  }
}

As long as you call that service method through a ScriptManager’s service proxy or using the correct parameters when using a library like jQuery, ASP.NET will automatically serialize the Person object and return it as raw, unencumbered JSON.

Accepting an object from the client-side

Accepting a Person object from the client-side works identically, in reverse. ASP.NET does a great job of matching JSON-serialized request parameters to .NET’s types, collections, and even your own custom objects.

For example this is how you could accept a Person object, which would even then allow you to call that object’s custom methods:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(Person PersonToSave)
  {
    // No, really, that's it (assuming Person has a Save() method).
    PersonToSave.Save();
  }
}

 



RIA Service Hosting :: How to send complex types to the Client

clock September 13, 2011 06:38 by author Administrator

 

Entity Framework 4 allows us to create complex types. Typically, such types are used to get the result of a stored procedure. However, when we try to send such a complex type using a WCF RIA Domain Service, the following error is encountered.



What to do? Adding attributes to EF designer generated classes is a bad idea; Also, we cannot use partial classes to add attributes to an already defined property. However, luckily, WCF RIA Services uses metadata classes in conjunction with the entity model classes and hence we can always create a meta data class for our complex type and decorate one of the fields with a
[Key] attribute. E.g., If our stored procedure is returning StoredProcedure_Result, then we may just need to add the following in our DomainService.metadata.cs file:



ASP.NET 4 Hosting :: Main Differences of Custom Control and User Control

clock August 23, 2011 07:57 by author Administrator

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:

UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.

Limitation of UserControl :

1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.

2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.

3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.

Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.

Note: Please don’t create a new custom control just to change the UI appearance as you can do this with any control available using custom Template

Limitation :

1. You have to define each behaviour for your control using Code. So it is hard way of achieving a behaviour.

2. Generic style is needed to be defined with your custom control to ensure that your control has a default look and feel.

Hence, based on your own requirement, if you are looking for a new behaviour which is different from existing userinterfaces available with WPF, you go for a Custom Control. A customControl can be styled and templated and best suited for a situation when you are building a Control Library.

On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don’t need to use it as a Control Library.

I hope this gives you a brief idea on the differences between the two.

Happy Coding.



BlogEngine 2.5 Hosting with ASPHostCentral.com

clock July 13, 2011 07:10 by author Administrator

Blogengine.Net 2.5 has just been released and the following are some the features you can find on this new blogging tool:

- Upgraded to .NET 4.0
- Multiple Blogs in Single Installation
- Razor Theme support (Razor theme included, "Garland-Revisited")
- Converted Admin pages to Razor (Dashboard, Extensions, Themes)
- Install Themes from the BlogEngine.NET Gallery while in the BlogEngine.NET control panel.
- New language resource files for Estonian and Polish, and other translations updated.
- Upgraded to jQuery 1.5.2.
- Upgraded to latest version of tinyMCE WYSIWYG editor, v3.4.3.1.
- Numerous fixes and improvements.

If you want to test-drive this new version, the release candidate can be downloaded here final version can be downloaded here.

Looks promising, so yesterday I downloaded the latest branch to get a little preview, and what did I see?

My very own Facebook thingy into action! It was a nice feeling to see it there, but I wished I could contribute more. See I've been working in my top secret underground lab to add Facebook comments to Blogengine.net, and while just hacking it in there is relatively easy to do, making it so that others can easily use the code for themselves is a second. Partially because Facebook's API is kind of...dodgy. In the way that it requires some XML namespaces added to the html tag, which is in the theme.

That sounds like a nightmare to me, because it would mean every user needs to change his or hers theme manually. "Luckily" it seems it also works with some Javascript, and I want to test that a bit more and see if I can get it worked out into a extension or even added to the build. But it seems with all my assignments I won't make that for the 2.5 release but oh well...there will be other releases.

In the meantime I hope Facebook finds out a way of doing things that is both clean and html 5 compliant.



Silverlight WCF Hosting :: Cross-Origin Resource Sharing (CORS) and WCF

clock July 5, 2011 08:45 by author Administrator

Yesterday I encountered the following question in the MSDN forums about calling a cross-domain WCF RESTful service from Chrome.

The problem with doing the above is because there is a cross-domain call to a WCF service. When you are using Chrome, the browser tries to find out if it can do the call by sending a cross-origin resource sharing (CORS) request, as explained in this article. In IE, you will most likely get a cross-domain exception.

After searching the web a bit, I found that the immediate solution is to change the supported HTTP method of the operation to “*”, and to add the special cross-origin headers to the outputted response, like so:

WebOperationContext.Current.OutgoingResponse.Headers.Add(
  "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(   "Access-Control-Allow-Methods", "POST"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
  "Access-Control-Allow-Headers", "Content-Type, Accept");

There are two problems with this solution:

You need to repeat these lines in each of your service methods.
The service method is called twice, once for the “preflight” request (the request with the OPTIONS HTTP verb), and a second time for the invocation itself.

So I took the time and written a special endpoint behavior that can be attached to any webHttpBinding based endpoint.

The code does the following:

1. Every response message gets the “Access-Control-Allow-Origin” header with the value of “*”, to tell the client that the service allowed the request from the client.

2. If the client sends a request to the service with the verb OPTIONS (this is referred to as a “preflight” request), the service will automatically return a 200 (ok) response with the required headers: “Access-Control-Allow-Headers” and “Access-Control-Allow-Methods” (in addition to the allow-origin header). Clients that look for the “allow” headers in the response will then send the original required request to the service.

The benefits of using this behavior is:

The code that returns the message with the headers is located in the behavior itself – no need to place it in each service method.

The behavior catches the OPTIONS request, and does not require running the service method twice.

You do not need to change any part of your service contract or service implementation. The behavior is only needed to be applied using configuration.

To implement this behavior I used a message inspector that checks the request and changes the response, and an operation invoker that wraps the unhandled operation invoker. The custom operation invoker handles the OPTIONS message requests, which otherwise would have caused the service to return an error message (because no method is set to handle “Options” requests).

The endpoint behavior can be attached to the endpoint through configuration, like so:

<behaviors>
  <endpointBehaviors>
    <behavior name="webSupport">
      <webHttp />
      <CorsSupport />
    </behavior>
  </endpointBehaviors>
</behaviors>

<extensions>
  <behaviorExtensions>
    <add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </behaviorExtensions>
</extensions>
<services>
  <service name="Service.JSonService">
    <endpoint address="http://localhost:8080" behaviorConfiguration="webSupport” binding="webHttpBinding" contract="Service.IJSonService" />
  </service>
</services>

Or, if you are using IIS to host your services, I also created a service host factory that creates a WebServiceHost and adds the behavior to every webHttpBinding based endpoint created by the host. To use it in your .svc file, just write something like this:

<%@ ServiceHost Language="C#" Debug="true" Service="Service.JSonService, Service" Factory="WebHttpCors.CorsWebServiceHostFactory, WebHttpCors" %>

To test the two hosts, open the webform1.aspx and change the target URL to access the IIS/self-hosted service.

Enjoy!



ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!

 

Calendar

<<  May 2024  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

Sign in