Category Archives: asp.net-mvc-4

Rewriting the url in mvc4 which is generating dynamically

My scenario is to rewrite the url which is dynamically generating based on the users login.For example my url is " mywebsite.com/controllername/methodname?id1=venkatesh%2Fevents" ,I want to change this url into "mywebsite.com/venkatesh/events. I have tried several scenario's but i didn't find proper solution. I tried the below code but it is not giving proper answer please suggest.

namespace MvcApplication3.Controllers
{

    [RouteArea("area")]
    [RoutePrefix("event",Precedence=1)]
    [RoutePrefix("student", Precedence = 2)]
    public class Default1Controller : Controller
    {
        //
        // GET: /Default1/
        [GET("venkatesh")]
      [GET("venkatesh-event",IgnoreAreaUrl=true)]
        public ActionResult Index()
        {

            ViewBag.info = "This is index method";
            return View();
        }

        //
        // GET: /Default1/Details/5
        [GET("event{id}")]
        public ActionResult Details(int id)
        {
            ViewBag.info = "This is details method"+id;
            return View();
        }

Rewriting the url in mvc4 which is generating dynamically

My scenario is to rewrite the url which is dynamically generating based on the users login.For example my url is " mywebsite.com/controllername/methodname?id1=venkatesh%2Fevents" ,I want to change this url into "mywebsite.com/venkatesh/events. I have tried several scenario's but i didn't find proper solution. I tried the below code but it is not giving proper answer please suggest.

namespace MvcApplication3.Controllers
{

    [RouteArea("area")]
    [RoutePrefix("event",Precedence=1)]
    [RoutePrefix("student", Precedence = 2)]
    public class Default1Controller : Controller
    {
        //
        // GET: /Default1/
        [GET("venkatesh")]
      [GET("venkatesh-event",IgnoreAreaUrl=true)]
        public ActionResult Index()
        {

            ViewBag.info = "This is index method";
            return View();
        }

        //
        // GET: /Default1/Details/5
        [GET("event{id}")]
        public ActionResult Details(int id)
        {
            ViewBag.info = "This is details method"+id;
            return View();
        }

mod_mono Error 503 after restarting Apache

I had a working mvc4-project running in Apache with mod_mono for quite some time. I hadn't touched Apache for a while, and for whatever reason, I decided to restart it. All of a sudden the site stopped working.

I get error 503 in my browser. The following is logged in Apache's error.log immediately when restarting Apache. Also, whenever I type in the url for the site:

    [ERROR] FATAL UNHANDLED EXCEPTION: System.IO.FileNotFoundException: Could not load file or assembly 'Mono.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756' or one of its dependencies.
    File name: 'Mono.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756'
      at (wrapper xdomain-invoke) System.AppDomain:DoCallBack (System.CrossAppDomainDelegate)
      at (wrapper remoting-invoke-with-check) System.AppDomain:DoCallBack (System.CrossAppDomainDelegate)
      at System.Web.Hosting.ApplicationHost.CreateApplicationHost (System.Type hostType, System.String virtualDir, System.String physicalDir) <0x41bbbd60 + 0x00b2d> in <filename unknown>:0
      at Mono.WebServer.VPathToHost.CreateHost (Mono.WebServer.ApplicationServer server, Mono.WebServer.WebSource webSource) <0x41bbaf70 + 0x000b7> in <filename unknown>:0
      at Mono.WebServer.Apache.Server.RealMain (System.String[] args, Boolean root, IApplicationHost ext_apphost, Boolean v_quiet) <0x41b5f3e0 + 0x006af> in <filename unknown>:0
      at (wrapper remoting-invoke-with-check) Mono.WebServer.Apache.Server:RealMain (string[],bool,Mono.WebServer.IApplicationHost,bool)
      at Mono.WebServer.Apache.Server.Main (System.String[] args) <0x41b5ed70 + 0x000e3> in <filename unknown>:0
.
.
.
 [:error] [pid 6850] Failed to connect to mod-mono-server after several attempts to spawn the process.

My virtualhosts file:

<VirtualHost *:80>   
  ServerName fta.domain.com
  ServerAlias fta.domain.com
  ServerAdmin [email protected]
  DocumentRoot /home/username/public_html/FifaTournamentApp
  # MonoServerPath can be changed to specify which version of ASP.NET is hosted
  # mod-mono-server1 = ASP.NET 1.1 / mod-mono-server2 = ASP.NET 2.0
  # For SUSE Linux Enterprise Mono Extension, uncomment the line below:
  # MonoServerPath Username "/opt/novell/mono/bin/mod-mono-server2"
  # For Mono on openSUSE, uncomment the line below instead:

MonoServerPath Username "/usr/bin/mod-mono-server4"

  # To obtain line numbers in stack traces you need to do two things:
  # 1) Enable Debug code generation in your page by using the Debug="true"
  #    page directive, or by setting <compilation debug="true" /> in the
  #    application's Web.config
  # 2) Uncomment the MonoDebug true directive below to enable mod_mono debugging
  #MonoDebug Username true

  # The MONO_IOMAP environment variable can be configured to provide platform abstraction
  # for file access in Linux.  Valid values for MONO_IOMAP are:
  #    case
  #    drive
  #    all
  # Uncomment the line below to alter file access behavior for the configured application
  MonoSetEnv Username MONO_IOMAP=all
  #
  # Additional environtment variables can be set for this server instance using
  # the MonoSetEnv directive.  MonoSetEnv takes a string of 'name=value' pairs
  # separated by semicolons.  For instance, to enable platform abstraction *and*
  # use Mono's old regular expression interpreter (which is slower, but has a
  # shorter setup time), uncomment the line below instead:
  # MonoSetEnv Username MONO_IOMAP=all;MONO_OLD_RX=1

  MonoApplications Username "/:/home/username/public_html/FifaTournamentApp"
  <Location "/">
    Allow from all
    Order allow,deny
    MonoSetServerAlias Username
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
  </Location>
  <IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
  </IfModule>

Just typing mod-mono-server4 in terminal seems to work fine:

mod-mono-server4
Listening on: /tmp/mod_mono_server
Root directory: /home/supporthjalpen/public_html/
Hit Return to stop the server.

Help with this is greatly appreciated!

How to fix rowscaps.ini does not contain a definition for capability ismobiledevice for userAgent Unknown after upgrade

Mono in Debian is used to host ASP.NET MVC4 application in Apache with mod_mono

Mono was ugraded to 4.2.2.10 by compiling from source using official instructions. Also XSP 4.2 was compiled and used.

After that invoking web application produces error

Value cannot be null.
Parameter name: browscaps.ini does not contain a definition for capability ismobiledevice for userAgent Unknown

probably at line

https://github.com/mono/mono/blob/b7a308f660de8174b64697a422abfc7315d07b8c/mcs/class/System.Web/System.Web/BrowserCapabilities.cs#L615

Stack trace is below. How to fix this ? In Mono 3.2.8 it works.

browsercap.ini file is present. This property defailt value is defined in CapabilityLoader.cs . So this exception does not occur. Also it looks like there is invalid spelling of file name browsercap.ini as browsercaps.ini in error message.

Value cannot be null.
Parameter name: browscaps.ini does not contain a definition for capability ismobiledevice for userAgent Unknown


System.ArgumentNullException: Value cannot be null.
Parameter name: browscaps.ini does not contain a definition for capability ismobiledevice for userAgent Unknown
  at System.Web.Configuration.HttpCapabilitiesBase.ReadBoolean (System.String key) [0x00016] in /usr/local/src/mono-4.2.2/mcs/class/System.Web/System.Web/BrowserCapabilities.cs:548 
  at System.Web.Configuration.HttpCapabilitiesBase.get_IsMobileDevice () [0x0000d] in /usr/local/src/mono-4.2.2/mcs/class/System.Web/System.Web.Configuration_2.0/HttpCapabilitiesBase.cs:383 
  at System.Web.HttpBrowserCapabilitiesWrapper.get_IsMobileDevice () [0x00000] in /usr/local/src/mono-4.2.2/mcs/class/System.Web.Abstractions/System.Web/HttpBrowserCapabilitiesWrapper.cs:195 
  at System.Web.WebPages.DisplayModeProvider.<.ctor>b__2 (System.Web.HttpContextBase context) <0x41bd3310 + 0x0001b> in <filename unknown>:0 
  at System.Web.WebPages.DefaultDisplayMode.CanHandleContext (System.Web.HttpContextBase httpContext) <0x41bd32c0 + 0x0002c> in <filename unknown>:0 
  at System.Web.WebPages.DisplayModeProvider+<>c__DisplayClass6.<GetAvailableDisplayModesForContext>b__5 (IDisplayMode mode) <0x41bd3290 + 0x00025> in <filename unknown>:0 
  at System.Linq.Enumerable+WhereSelectListIterator`2[TSource,TResult].MoveNext () [0x00048] in /usr/local/src/mono-4.2.2/external/referencesource/System.Core/System/Linq/Enumerable.cs:371 
  at System.Linq.Enumerable.FirstOrDefault[TSource] (IEnumerable`1 source, System.Func`2 predicate) [0x00041] in /usr/local/src/mono-4.2.2/external/referencesource/System.Core/System/Linq/Enumerable.cs:960 
  at System.Web.WebPages.DisplayModeProvider.GetDisplayInfoForVirtualPath (System.String virtualPath, System.Web.HttpContextBase httpContext, System.Func`2 virtualPathExists, IDisplayMode currentDisplayMode, Boolean requireConsistentDisplayMode) <0x41bd2b70 + 0x0023f> in <filename unknown>:0 
  at System.Web.WebPages.DisplayModeProvider.GetDisplayInfoForVirtualPath (System.String virtualPath, System.Web.HttpContextBase httpContext, System.Func`2 virtualPathExists, IDisplayMode currentDisplayMode) <0x41bd2b00 + 0x0003f> in <filename unknown>:0 
  at System.Web.WebPages.WebPageRoute.GetRouteLevelMatch (System.String pathValue, IEnumerable`1 supportedExtensions, IVirtualPathFactory virtualPathFactory, System.Web.HttpContextBase context, System.Web.WebPages.DisplayModeProvider displayModeProvider) <0x41bd27e0 + 0x00163> in <filename unknown>:0 
  at System.Web.WebPages.WebPageRoute.MatchRequest (System.String pathValue, IEnumerable`1 supportedExtensions, IVirtualPathFactory virtualPathFactory, System.Web.HttpContextBase context, System.Web.WebPages.DisplayModeProvider displayModes) <0x41bd24f0 + 0x00193> in <filename unknown>:0 
  at System.Web.WebPages.WebPageRoute.DoPostResolveRequestCache (System.Web.HttpContextBase context) <0x41bd0a10 + 0x000d7> in <filename unknown>:0 
  at System.Web.WebPages.WebPageHttpModule.OnApplicationPostResolveRequestCache (System.Object sender, System.EventArgs e) <0x41bd0640 + 0x000ab> in <filename unknown>:0 
  at System.Web.HttpApplication+<RunHooks>c__Iterator0.MoveNext () [0x001ba] in /usr/local/src/mono-4.2.2/mcs/class/System.Web/System.Web/HttpApplication.cs:1030 
  at System.Web.HttpApplication+<Pipeline>c__Iterator1.MoveNext () [0x006f3] in /usr/local/src/mono-4.2.2/mcs/class/System.Web/System.Web/HttpApplication.cs:1238 
  at System.Web.HttpApplication.Tick () [0x00000] in /usr/local/src/mono-4.2.2/mcs/class/System.Web/System.Web/HttpApplication.cs:927 
GET /sba/Detail?_entity=DokVL&_id=31187 HTTP/1.0

URL rewrite/redirect through FTP-access in ASP4.0 / IIS8.0?

I am to redirect some URLs from an old site to a new site on a different domain name. Normally I would do this editing/uploading a .htaccess file on Apache servers. Piece of cake.

Now, I've been given FTP-access to the old server. However, its a ASP4.0 / IIS8.0 server and I cannot use the .htaccess-method it seems.

My questions therefore: is there a solution to this through only FTP-access? Should I upload/edit a specific file? I have never worked with ASP-servers.

Help is much appreciated, thanks.

Signalr problems with mod_mono and apache

I have simple MVC4 project with simple Signalr chat. And i want to port this app on mono (Debian+mod_mono+apache2). When i use just XSP4 server, it works fine, but when i use mod_mono+apache2, i get error "No 'Access-Control-Allow-Origin' header is present on the requested resource."

My Startup class:

var policy = new CorsPolicy
        {
            AllowAnyHeader = true,
            AllowAnyMethod = true,
            AllowAnyOrigin = true,
            SupportsCredentials = true
        };

        app.UseCors(new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context => Task.FromResult(policy)
            }
        });
        app.MapSignalR();

My Global.asax: WebApp.Start<Startup>("http://localhost:55555");

My View:

@{
    ViewBag.Title = "ChatSignalr";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ChatSignalr</h2>

<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="http://localhost:55555/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            $.connection.hub.url = 'http://localhost:55555/signalr';
            var chat = $.connection.chatHub;
            $.connection.chatHub.logging = true;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

My apache2 site configuration: http://pastebin.com/KvJ3NChp

I think that i have to set "Header set Access-Control-Allow-Origin "*"" for localhost:55555 on Apache2, but how should i do this? And why only XSP4 works fine with CorsPolicy properties, but mod_mono+apache2 doesnt?

Url rewriting in IIS throws error

I am trying to rewrite all my urls to a specific action and a controller in my ASP.NET MVC app . The code I am using in web.config since I want url rewriting to happen in iis.

<rewrite>
          <rules>
              <rule name="DynamicRewrite" stopProcessing="true">
                  <match url="(.*)" />
                  <action type="Rewrite" url="/Sample/Index" />
              </rule>
          </rules>
      </rewrite>

But I am always getting this error.It works fine when I remove this section. The error is

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

What am I doing wrong ?

FormsAuthentication of ASP.NET app running on Mono

I have an ASP.NET MVC4 web application which was developed using Visual Studio in Windows. I am trying to deploy it to an Apache server running on Ubuntu. I am settling for getting it working on xsp for time being, since that seems simpler to start.

The latest in a long series of errors is this:

Missing method System.Web.Security.FormsAuthentication::get_IsEnabled()
in assembly /usr/lib/mono/gac/System.Web/4.0.0.0__b03f5f7f11d50a3a/System.Web.dll, 
referenced in assembly /tmp/username-temp-aspnet-0/e475125c/assembly/shadow/5cf10065/81ba6702_dd4b6767_00000001/System.Web.Http.WebHost.dll

I have deleted the < authentication mode="..">... tags from the web.config file, so I'm not sure why anything is trying to call FormsAuthentication. The error appears to be coming from the mono .dlls.

What is causing this error, and what do I need to do to fix it?

How to avoid apache to stop responding in MVC application

ASP.NET MVC4 application is running using Apache, Mono 3.2.8 and mod_mono in Debian x64 Linux

Some times in every month server stops responding:

There is also mod_mono control panel and apache server status module istalled.

Typing mysite.com, mysite.com/server-status or mysite.com/mono in browser waits forever. top shows that cpu usage is almost zero and there are lot of free memory.

There is no special timeout in web.config so every thread should terminated after 110 seconds even if it hangs. It looks like apache stops responding, maybe max number of conncurrent connections is reached. This is shopping cart application and search engine robots make huge amount of calls to it in every day.

How to fix or find reason of those hangups?

Is it reasonable to create cron job

wget --tries=1 --timeout=5  www.mysite.com || /etc/init.d/apache2 restart

which runs after every 10 minutes ? Will this restart apache if hangup occurs ?

Using crontab -e and adding line

10 * * * * wget --tries=1 --timeout=5  www.mysite.com || /etc/init.d/apache2 restart

runs check only once per hour. How to run check after every 10 minutes ?

apache2 -V returns:

Server version: Apache/2.2.22 (Debian)
Server built:   Feb  1 2014 21:26:17
Server's Module Magic Number: 20051115:30
Server loaded:  APR 1.4.6, APR-Util 1.4.1
Compiled using: APR 1.4.6, APR-Util 1.4.1
Architecture:   64-bit
Server MPM:     Worker
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/worker"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/apache2"
 -D SUEXEC_BIN="/usr/lib/apache2/suexec"
 -D DEFAULT_PIDLOG="/var/run/apache2.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="mime.types"
 -D SERVER_CONFIG_FILE="apache2.conf"