How to re-implement legacy aspx with ServiceStack and maintain the address? - asp.net

Is it possible to keep the following address and re-implement it with ServiceStack?
http://example.com/Routing/LeadPost.aspx?LeadType=AAA&MYId=3000
I don't have access to the original code as it was a 3rd party who created it, but I do know what the post to it, a gigantic xml package. This I have mimicked perfectly with a clean request DTO and service, but I'm not clear on the addressing part, or if it's even plausible. Below is my implementation so far.
public class Service : ServiceStack.Service
{
public IMessageQueueClient MessageQueueClient { get; set; }
public object Post(LeadInformation request)
{
if (request == null) throw new ArgumentNullException("request");
var sw = Stopwatch.StartNew();
MessageQueueClient.Publish(request);
return new LeadInformationResponse
{
TimeTakenMs = sw.ElapsedMilliseconds,
};
}
}
Thank you,
Stephen

You can use this route definition to handle the Legacy ASP.NET WebForms Request:
[Route("/Routing/LeadPost.aspx")]
public class LegacyLeadPost
{
public string LeadType { get; set; }
public int MyId { get; set; }
}
Which will let you handle the desired route with LeadType and MyId properties populated:
/Routing/LeadPost.aspx?LeadType=AAA&MYId=3000
An alternative approach is to use a WebForms Page and call into ServiceStack, the ServiceStack Integration docs explores the different ways from accessing ServiceStack from external ASP.NET MVC or WebForms Web Frameworks.

When you installed ServiceStack (at least up to version 3, which is what I last used), it adds something to your application's Web.Config file that looks like:
<system.web>
<httpHandlers>
<add path="somePath/*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
If you modify the path attribute to match your legacy URL, it may work. Then again, without knowing what other HttpHandlers are set up for your application, it is impossible to tell for sure. Also keep in mind that you may introduce conflicts, because there is an HttpHandler that passes all .aspx urls to the .NET webforms Page base class and all the other code-behind files in your application.

Related

ASP.NET 4.6 MVC Output Caching with Razor Syntax Issues

I have an ASP.NET 4.6 project that uses MVC controllers that return my views and WebAPI Controllers that return data.
I want to add output caching to my MVC controllers because I've done a few tests and the performance difference on page load is massive.
[OutputCache(CacheProfile = "PageCache")]
public ActionResult Home()
{
return View("~/Views/Home/Index.cshtml");
}
The only challenge I'm facing is that the razor syntax on the views is also cached.
For example if user 1 loads a route, user 2 will get the same route with the username injected from user 1.
Besides getting rid of all the razor syntax in the pages, what are my options? Does anyone have a good solution to this problem?
You can use VaryByCustom or VaryByParam attributes. The following code is the cache based on the parameter 'id'.
[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult Details(int id)
{
ViewData.Model = _dataContext.Movies.SingleOrDefault(m => m.Id == id);
return View();
}
You can create a cache profile also in the web.config file
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Cache1Hour" duration="3600" varyByParam="none"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
For more info check this Link
You should not cache user information on the server, it should be cached on the client.
Please take a look at this document.
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs

Correct way of adding Page Method to ASP MVC project?

I'm just getting started with ASP.NET and the MVC model. I've worked my around the basic concepts and have a few models, controllers, and views working fine. I know how to add Web Methods and Page Methods to a Web Service, but cannot figure it out for MVC projects.
I (think) I need to add a Page Method to my project as the correct way of responding to AJAX requests. This is what my controller looks like:
namespace MyProject
{
public class OrderController : Controller
{
public ActionResult Place (ProductSku sku)
{
var order = Order.NewOrder(sku);
var db = new SystemDiscsLib.Database();
db.SaveOrder(order);
return View(order);
}
[WebMethod]
public static string GetDate ()
{
return DateTime.Now.ToString();
}
POSTing to /Order/Place works fine, and the view is created displaying the contents of Views/Order/Place.aspx and everyone is happy. However, any requests made to /Order/GetDate fail with a The resource cannot be found error. I (think) I have correctly enabled Page Methods by adding this to my Web.config, under system.web:
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
I do not have a view called GetDate as I don't want a view, I'll just be returning JSON data. I intend to use JQuery, so I didn't do the EnablePageMethods and ScripManager stuff, per this article.
PageMethods are for WebForms, not MVC. Change your method to look more like this:
public JsonResult GetDate()
{
return Json(DateTime.Now.ToString());
}
Note that the method is no longer static, and you should not use the [WebMethod] attribute.

Very simple single user login in ASP.NET MVC2?

I'm building my site, and I want to restrict a part of my site (The admin parts) from normal public display.
I am using LINQ for database access.
I have a Service class to handle calls to the database through LINQ
I have the whole site running, except for the Login part.
So far I have only been able to find examples using MembershipProvider and/or RoleProviders etc. And to be honest, it does seem like too much work for what I want. All this has to do is to let you in if you type the correct password in the input fields.
Can i really not avoid the Providers?
Since you only have a single user you don't need to create a database dependency. You can make a very simple authorization service based off of a hard coded credentials. For example,
public class AuthorizationService{
private AuthorizationService(){}
public static readonly AuthorizationService Instance = new AuthorizationService();
private const string HardCodedAdminUsername = "someone";
private const string HardCodedAdminPassword = "secret";
private readonly string AuthorizationKey = "ADMIN_AUTHORIZATION";
public bool Login(string username, string password, HttpSessionStateBase session){
if(username.ToLowerInvariant().Trim()==HardCodedAdminUsername && password.ToLowerInvariant().Trim()==HardCodedAdminPassword){
session[AuthorizationKey] = true;
return true;
}
return false;
}
public void Logout(HttpSessionStateBase session){
session[AuthorizationKey] = false;
}
public bool IsAdmin(HttpSessionStateBase session){
return session[AuthorizationKey] == true;
}
}
Then you can build a custom IAuthorizationFilter like:
public class SimpleAuthFilterAttribute: FilterAttribute, IAuthorizationFilter{
public void OnAuthorization(AuthorizationContext filterContext){
if(!AuthorizationService.Instance.IsAdmin(filterContext.HttpContext.Session)){
throw new UnauthorizedAccessException();
}
}
}
Then all you have to do is decorate the protected controller actions with the SimpleAuthFilter and you're application's login suddenly works. Yay! (Note, I wrote all this code in the StackOverflow answer window, so you may need to clean up typos, etc. before it actually works)
Also, you could refactor this to omit the username if you find that unnecessary. You will need to create a controller action for Login and Logout that make the corresponding calls to the AuthorizationService, if you want your protected controller actions to ever be accessible.
Its worth building a light-weight Membership Provider with minimal implementation; GetUser, ValidateUser etc methods. YOu dont need to implement the whole thing. It just helps with authorising pages and checking User.Identity etc when needed. You also dont need the RoleProvider or ProfileProvider to do this.
Its also scalable for the future.
UPDATE
You just need to implement the core methods to valudate and get the user and insert your own validation/data access code.
Something like this....
web.config settings:
<membership defaultProvider="ApplicationMembershipProvider">
<providers>
<clear/>
<add name="ApplicationMembershipProvider" type="YourNamespace.ApplicationMembershipProvider"/>
</providers>
</membership>
Login Code:
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
}
You can set the status (logged in or not) in a session variable. Set the variable to true if the user entered the correct password, then on every page you want to restrict access, check if the variable is true.
#KristianB a while ago I gave an answer to this SO question. I believe it may be useful since it's very straightforward to implement and at the same time it's better than hardcoding a username and a password in your code.
Good luck!

profile in asp.net MVC [duplicate]

I don't know what I am missing, but I added Profile properties in the Web.config file but cannot access Profile.Item in the code or create a new profile.
I had the same problem today, and learned a lot.
There are two kinds of project in Visual Studio -- "Web Site Projects" and "Web Application Projects." For reasons which are a complete mystery to me, Web Application Projects cannot use Profile. directly... the strongly-typed class is not magically generated for you from the Web.config file, so you have to roll your own.
The sample code in MSDN assumes you are using a Web Site Project, and they tell you just to add a <profile> section to your Web.config and party on with Profile.property, but that doesn't work in Web Application Projects.
You have two choices to roll your own:
(1) Use the Web Profile Builder. This is a custom tool you add to Visual Studio which automatically generates the Profile object you need from your definition in Web.config.
I chose not to do this, because I didn't want my code to depend on this extra tool to compile, which could have caused problems for someone else down the line when they tried to build my code without realizing that they needed this tool.
(2) Make your own class that derives from ProfileBase to represent your custom profile. This is easier than it seems. Here's a very very simple example that adds a "FullName" string profile field:
In your web.config:
<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="sqlServerMembership" />
</providers>
</profile>
In a file called AccountProfile.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace YourNamespace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get { return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName)); }
}
public string FullName
{
get { return ((string)(base["FullName"])); }
set { base["FullName"] = value; Save(); }
}
// add additional properties here
}
}
To set a profile value:
AccountProfile.CurrentUser.FullName = "Snoopy";
To get a profile value
string x = AccountProfile.CurrentUser.FullName;
Web Application Projects can still use the ProfileCommon object but only at runtime. The code for it is just not generated in the project itself but the class is generated by ASP.Net and is present at runtime.
The simplest way to get to object is to use a dynamic type as demonstrated below.
In the Web.config file declare the profile properties:
<profile ...
<properties>
<add name="GivenName"/>
<add name="Surname"/>
</properties>
Then to access the properties:
dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";
To save changes to profile properties:
profile.Save();
The above works fine if you are comfortable using dynamic types and don't mind the lack of compile-time checking and intellisense.
If you use this with ASP.Net MVC you have to do some additional work if you pass the dynamic profile object to your views since the HTML helper methods don't play well with "model" objects that are dynamic. You will have to assign profile properties to statically typed variables before passing them to HTML helper methods.
// model is of type dynamic and was passed in from the controller
#Html.TextBox("Surname", model.Surname) <-- this breaks
#{ string sn = model.Surname; }
#Html.TextBox("Surname", sn); <-- will work
If you create a custom profile class, as Joel described above, ASP.Net will still generate the ProfileCommon class but it will inherit from your custom profile class. If you don't specify a custom profile class ProfileCommon will inherit from System.Web.Profile.ProfileBase.
If you create your own profile class make sure that you don't specify profile properties in the Web.config file that you've already declared in your custom profile class. If you do ASP.Net will give a compiler error when it tries to generate the ProfileCommon class.
Profile can be used in Web Application Projects too.
The properties can be defined in Web.config at design time or programmatically. In Web.config:
<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
</providers>
<properties>
<add name="FirstName"/>
<add name="LastName"/>
<add name ="Street"/>
<add name="Address2"/>
<add name="City"/>
<add name="ZIP"/>
<add name="HomePhone"/>
<add name="MobilePhone"/>
<add name="DOB"/>
</properties>
</profile>
or Programmatically, create the profile section by instantiating a ProfileSection and creating individual properties using ProfilePropertySettings and ProfilePropertySettingsColletion, all of which are in System.Web.Configuration Namespace.
To use those properties of the profile, use System.Web.Profile.ProfileBase Objects. The profile properties cannot be accessed with profile. syntax as mentioned above, but can be easily done by instantiating a ProfileBase and using SetPropertyValue("PropertyName") and GetPropertyValue{"PropertyName") as follows:
ProfileBase curProfile = ProfileBase.Create("MyName");
or to access the profile of current user:
ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);
curProfile.SetPropertyValue("FirstName", this.txtName.Text);
curProfile.SetPropertyValue("LastName", this.txtLname.Text);
curProfile.SetPropertyValue("Street", this.txtStreet.Text);
curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
curProfile.SetPropertyValue("DOB", txtDob.Text);
curProfile.Save();
When you create a new Web site project in Visual Studio then the object that is returned from Profile will be (automatically) generated for you. When you create a Web application project or an MVC project, you will have to roll your own.
This probably sounds more difficult than it is. You need to do the following:
Create a database using aspnet_regsql.exe This tool is installed along with the .NET framework.
Write a class that derives from ProfileGroupBase or install the Web Profile Builder (WPB) that can generate the class for you from the definition in Web.Config. I have been using WPB for a while and up until now it has done what is expected of it. If you have a lot of properties, using WPB can save quite a bit of time.
Make sure the connection to the database is properly configured in Web.Config.
Now you are set to create an instance of your profile class (in the controller)
You will probably need the profile property values in your views. I like to pass the profile object itself along to the view (not individual properties).
If you are using a web application project, you cannot access the Profile object at design-time out-of-the-box. Here is a utility that supposedly does it for you: http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx. Personally, that utility caused an error in my project so I ended up rolling my own profile class to inherit from ProfileBase. It was not hard to do at all.
MSDN walkthrough for creating a custom class (a.k.a. Joel's method):
http://msdn.microsoft.com/en-us/magazine/cc163624.aspx
I was also running through the same issue. But instead of creating a class which inherits from ProfileBase, I used the HttpContext.
Specify properties in web.config file as follows : -
Now, write the following code : -
Compile and run the code. You will get following output: -
The Web Profile Builder worked great for me. The class it generated has a lot more in it than as described by Joel's post. Whether or not its actually needed or useful I dont know.
Anyway for those looking for an easy way to generate the class, but not wanting to have an external build tool dependency you can always
use the web profile builder
delete all trace of it!
keep using the generated Profile class
OR (untested but may just work)
create a web site project
create your element
snap the generated class and copy it over to your web project project
if this second approach does work can someone let me know for future reference
Just want to add to Joel Spolsky's answer
I implemented his solution, working brilliantly btw - Cudos!
For anyone wanting to get a user profile that's not the logged in user I used:
web.config:
<connectionStrings>
<clear />
<add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
</connectionStrings>
and
<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
<providers>
<clear/>
<add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
</providers>
And then my custom class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace NameSpace
{
public class AccountProfile : ProfileBase
{
static public AccountProfile CurrentUser
{
get
{
return (AccountProfile)
(ProfileBase.Create(Membership.GetUser().UserName));
}
}
static public AccountProfile GetUser(MembershipUser User)
{
return (AccountProfile)
(ProfileBase.Create(User.UserName));
}
/// <summary>
/// Find user with matching barcode, if no user is found function throws exception
/// </summary>
/// <param name="Barcode">The barcode to compare against the user barcode</param>
/// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
static public AccountProfile GetUser(string Barcode)
{
MembershipUserCollection muc = Membership.GetAllUsers();
foreach (MembershipUser user in muc)
{
if (AccountProfile.GetUser(user).Barcode == Barcode)
{
return (AccountProfile)
(ProfileBase.Create(user.UserName));
}
}
throw new Exception("User does not exist");
}
public bool isOnJob
{
get { return (bool)(base["isOnJob"]); }
set { base["isOnJob"] = value; Save(); }
}
public string Barcode
{
get { return (string)(base["Barcode"]); }
set { base["Barcode"] = value; Save(); }
}
}
}
Works like a charm...
Great post,
Just a note on the web.config
if you dont specify the inherit attribute in the profile element
you will need to specify each indiviudal profile property inside the profile
element on the web.config as below
<properties>
<clear/>
<add name="property-name-1" />
<add name="property-name-2" />
..........
</properties>

How to use System.Web.Routing to not URL rewrite in Web Forms?

I am using System.Web.Routing with ASP.NET (3.5) Web Forms that will URL rewrite the following URL from
http://www.myurl.com/campaign/abc
to
http://www.myurl.com/default.aspx?campaign=abc
The code is as below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add("CampaignRoute", new Route
(
"{campaign_code}",
new CustomRouteHandler("~/default.aspx")
));
}
IRouteHandler implementation:
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
VirtualPath = virtualPath;
}
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
if (requestContext.RouteData.Values.ContainsKey("campaign_code"))
{
var code = requestContext.RouteData.Values["campaign_code"].ToString();
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
"?campaign=" + code));
}
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
However I noticed there are too many things to change on my existing aspx pages (i.e. links to javascript, links to css files).
So I am thinking if there's a way to keep above code but in the end rather than a rewrite just do a Request.Redirect or Server.Transfer to minimize the changes needed. So the purpose of using System.Web.Routing becomes solely for URL friendly on the first entry.
How to ignore the rest of the patterns other than specificed in the code?
Thanks.
Using rewriting combined with ASP.NET URL Routing is not recommended because some implementations of ASP.NET URL Routing internally use rewriting as well (it depends on the version of ASP.NET). The combination of two different components using rewriting can cause conflicts (though I'm not 100% sure that that's why you're seeing this problem).
Regarding using transfer/redirect/rewrite:
My strongest recommendation would be to not use any of them! Instead of redirecting (or anything else) just let the page be called directly by ASP.NET by returning it from the IRouteHandler, much as you are already doing (just without the call to Rewrite). As long as your IRouteHandler saves the RouteData somewhere, the Page can then get the data from the route and you should be good to go.
Take a look at Phil Haack's Web Form routing sample to see an example of how to save the route data (or just use his code!).
Regarding ignoring patterns:
You can use an IRouteConstraint to constrain which URLs match your route. There is a built-in default route constraint implementation that uses regular expressions, but you can also write custom route constraints. Here is an example:
Route r = new Route(...);
r.Constraints = new RouteValueDictionary(new {
campaign_code = "\d{5}", // constrain to 5-digit numbers only
other_value = new CustomRouteConstraint(), // call custom constraint
});
CustomRouteConstraint is a class that you can write that derives from IRouteConstraint.
One thing I should note about static files such as CSS and JPG files is that by default they are always excluded from routing. By default routing ignores patterns that exactly match physical files on disk. You can change this behavior by setting RouteTable.Routes.RouteExistingFiles = true, but that is not the default.

Resources