Rectangle 27 139

You can use the ActionName attribute like so:

[ActionName("My-Action")]
public ActionResult MyAction() {
    return View();
}

Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods.

There isn't such a simple solution for controllers.

Now with MVC5, Attribute Routing has been absorbed into the project. You can now use:

[Route("My-Action")]

For controllers, you can apply a RoutePrefix attribute which will be applied to all action methods in that controller:

[RoutePrefix("my-controller")]

One of the benefits of using RoutePrefix is URL parameters will also be passed down to any action methods.

[RoutePrefix("clients/{clientId:int}")]
public class ClientsController : Controller .....
[Route("edit-client")]
public ActionResult Edit(int clientId) // will match /clients/123/edit-client

This is the real answer. Not sure why Phil didn't add this info

Nice tip. Just to add: When you do this with the default View() invocation, MVC will search for "My-Action.aspx" somewhere in the Views folder, not "MyAction.aspx," unless you explicitly specify the original name.

@Eduardo I think the ActionName attribute was added for Preview 5, which came out just after Phil's post.

How do you explicitly specify the view file name? Do I have to change the views file name to My-Action.aspx?

@LordofScripts - make sure that you've configured routing appropriately with: routes.MapMvcAttributeRoutes();

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 14

You could create a custom route handler as shown in this blog:

public class HyphenatedRouteHandler : MvcRouteHandler{
        protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
        {
            requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
            return base.GetHttpHandler(requestContext);
        }
    }
routes.Add(
            new Route("{controller}/{action}/{id}", 
                new RouteValueDictionary(
                    new { controller = "Default", action = "Index", id = "" }),
                    new HyphenatedRouteHandler())
        );

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 9

Uppercase urls are problematic because cookie paths are case-sensitive, most of the internet is actually case-sensitive while Microsoft technologies treats urls as case-insensitive. (More on my blog post)

To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.

in the Package Manager Console:

Install-Package LowercaseDashedRoute

After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:

routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);

That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.

After trying about a dozen of the other solutions I found online, this was the first one that actually worked for me with MVC5.Thanks

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 7

Here's what I did using areas in ASP.NET MVC 5 and it worked liked a charm. I didn't have to rename my views, either.

public static void RegisterRoutes(RouteCollection routes)
    {
        // add these to enable attribute routing and lowercase urls, if desired
        routes.MapMvcAttributeRoutes();
        routes.LowercaseUrls = true;

        // routes.MapRoute...
    }
[RouteArea("SampleArea", AreaPrefix = "sample-area")]
[Route("{action}")]
public class SampleAreaController: Controller
{
    // ...

    [Route("my-action")]
    public ViewResult MyAction()
    {
        // do something useful
    }
}

The URL that shows up in the browser if testing on local machine is: localhost/sample-area/my-action. You don't need to rename your view files or anything. I was quite happy with the end result.

After routing attributes are enabled you can delete any area registration files you have such as SampleAreaRegistration.cs.

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 3

[RoutePrefix("dogs-and-cats")]
public class DogsAndCatsController : Controller
{
    [HttpGet("living-together")]
    public ViewResult LivingTogether() { ... }

    [HttpPost("mass-hysteria")]
    public ViewResult MassHysteria() { }
}

To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the AttributeRouting project (also available as a nuget). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.

Wow, no ones mentioned the Ghostbusters reference?

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 1

You could write a custom route that derives from the Route class GetRouteData to strip dashes, but when you call the APIs to generate a URL, you'll have to remember to include the dashes for action name and controller name.

Phil is right (as usual). There's a great example that I can't take credit for, but I'm grateful I found. It's by an MVP, and you can find it here.

Here is my NuGet package for this implementation: nuget.org/packages/LowercaseDashedRoute Don't forget to read the README on GitHub (via Project Info link on NuGet page)

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 1

You can define a specific route such as:

routes.MapRoute(
    "TandC", // Route controllerName
    "CommonPath/{controller}/Terms-and-Conditions", // URL with parameters
    new {
        controller = "Home",
        action = "Terms_and_Conditions"
    } // Parameter defaults
);

Similarly, using AttributeRouting allows you to specify any route name you want, with the added benefit of knowing exactly which route your action is associated with.

Asp.Net MVC: How do I enable dashes in my urls? - Stack Overflow

asp.net-mvc
Rectangle 27 58

ExtensionlessUrlHandler-Integrated-4.0
DELETE
PUT

You've mention on a deleted post you were running on a 2008 server right? Try removing webDav role, or disable it from your site config: on system.webServer -> modules section, remove WebDAVModule module:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

I did this stuffs before. But still not works ):

+Daniel I did. Still not works. I see just now, when I make a DELETE request, and while it's trying to do request I click another link, and the DELETE request sone fine! My english is too bad, do you understande what is my mean? See: 1- Make a DELETE request, 2- It's trying, 3- I click another link, 4- The DELETE request (that was trying) get succeed!

It's important to remove both the module and the handler. I missed removing the module the first time in IIS and was very confused for awhile!

c# - How do I enable HTTP PUT and DELETE for ASP.NET MVC in IIS? - Sta...

c# asp.net-mvc-3 iis-7.5 http-put http-delete
Rectangle 27 13

If you are getting following error in your production environment in the asp.net web api on PUT or DELETE though these methods are working fine locally.

405 - http verb used to access this page is not allowed.

<system.webServer>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
</system.webServer>

Cause: webDAV module blocks PUT/DELETE methods by default. So first remove this module and its handler. We first remove any existing ExtensionlessUrlHandler-Integrated-4.0 settings and add it with desired path and verbs.

c# - How do I enable HTTP PUT and DELETE for ASP.NET MVC in IIS? - Sta...

c# asp.net-mvc-3 iis-7.5 http-put http-delete
Rectangle 27 3

You just need to add the following lines of code in your web.config

<system.webServer>
 <security>
    <requestFiltering>
        <verbs allowUnlisted="false">
            <add verb="GET" allowed="true" />
            <add verb="POST" allowed="true" />
            <add verb="DELETE" allowed="true" />
            <add verb="PUT" allowed="true" />
        </verbs>
    </requestFiltering>
</security>
<modules>
    <remove name="WebDAVModule" />
</modules>
<handlers>
    <remove name="WebDAV" />
</handlers>

Not working for me. I hosted wordpress on mysite.com/wordpress/index.php/wp-json/wp/v2/posts/649?force=true. I try to delete but I get 405 method not allowed.

Is this version specific? It seems like I see this same answer all over the web, but in IIS 8.0 it just causes a 500 internal server error. Maybe we need a new solution.

c# - How do I enable HTTP PUT and DELETE for ASP.NET MVC in IIS? - Sta...

c# asp.net-mvc-3 iis-7.5 http-put http-delete
Rectangle 27 2

$.ajax({ 
    url: this.href + "?linkid=" + $(link).data("linkid"), 
    cache: false, 
    type: 'DELETE', 
    // data: { linkid: $(link).data("linkid") }, 
    beforeSend: function () { 
        // doing something in UI 
    }, 
    complete: function () { 
        // doing something in UI 
    }, 
    success: function (data) { 
        // doing something in UI 
    }, 
    error: function () { 
        // doing something in UI 
    } 
});

Do you have any explaination why a DELETE call, can't have Form Data? While on local it had and worked fine?

@Neal yep you are right. Post your comment as an answer that I can accept it

@Neal - There is nothing in the HTTP 1.1 spec that forbids or even suggests that a DELETE request should not have a message body. Can you provide a link indicating otherwise?

c# - How do I enable HTTP PUT and DELETE for ASP.NET MVC in IIS? - Sta...

c# asp.net-mvc-3 iis-7.5 http-put http-delete
Rectangle 27 20

I guess the specific package you are trying to install needs to run a powershell script and for some reason powershell execution is disabled on your machine. You can search google on "how to enable powershell" for a complete guide but generaly it goes like this:

  • Open up a powershell command window (just search for powershell after pressing windows start button)

This issue does not affect the server you are planing to install your application on.

My execution policy is already RemoteSigned... but still received this error...

Worked like a charm!

@RosdiKasim Same here, solution did not work for me. Any idea hot to tackle this?

asp.net mvc - Nuget give this error "ps1 cannot be loaded because runn...

asp.net-mvc powershell nuget
Rectangle 27 15

RegisterGlobalFilters
FiltersConfig
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new RequireHttpsAttribute());
    }
}

asp.net mvc - How do I enable ssl for all controllers in mvc applicati...

asp.net-mvc oauth-2.0 asp.net-mvc-5 ssl-certificate openid
Rectangle 27 2

Fiddler is doing a man in the middle scenario to snoop the traffic and fiddler can do this when you enable "decrpt https traffic in fiddler options" .

asp.net mvc - Password is visible when i post the form in https with m...

asp.net-mvc ssl iis https
Rectangle 27 13

This is an old question but it was still in the top 3 results on searches for "web api application insights owin". After lots of searching and not a lot of answers that didn't require us to write our own middleware or explictly instrumenting everything. We came across an extension package that made things super simple:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseApplicationInsights();

        // rest of the config here...
    }
}
<TelemetryInitializers>
    <!-- other initializers.. -->
    <Add Type="ApplicationInsights.OwinExtensions.OperationIdTelemetryInitializer, ApplicationInsights.OwinExtensions"/>
</TelemetryInitializers>

then retrieve from owin middleware with Request.GetOwinContext().Get<TelemetryClient>();

asp.net mvc - How do I enable Application Insights server telemetry on...

asp.net-mvc asp.net-web-api katana azure-application-insights
Rectangle 27 8

AI uses httpmodule to collect information on begin request and send it on end request. As described here Owin/Katana uses middelwares to execute logic on a different stages. As most of AI auto collection logic is internal you cannot reuse it in your middleware. But you can instrument your code yourself. Create TelemetryClient from your code and start sending Request, Traces and Exceptions (like described here)

So basically you are saying that it's not possible to integrate AI in a WebAPI project that uses OWIN/Katana without code modifications? I'd really like to avoid that, since what we need now is just a temporary profiling to detect and fix the slowdown and then remove AI from the projects again. If code modifications are needed, it means we will have to deploy an entirely new version to production just to diagnose the problem, which is a big hassle at the moment.

AI is not a profiler. It is SDK for code instrumentation. There is out of the box support for asp.net applications that use regular IIS stack. If onBegin and onEnd are not called, AI code is not invoked.

I understand that, but our current scenario would greatly benefit from the Application Insights Monitor telemetry on a live environment. If we go the code approach now, it means we will have to come up with a plan on how to manage the keys over all different environments, how to set them, where in the code this will need to be, etc. Unfortunately we don't have time for these tasks right now and we need to solve the problem as quick as possible, so it's very sad that this process does not work. Are you from the dev team? Have you considered supporting katana out of the box somehow?

Biggest problem is the lack of available documentation about this subject.

It smells to me like the AI team are expecting the community to pick up the slack around OWIN/Katana and AI integration and I kinda get that. For me, the problem was discovering that AI would 'just work' for my traditional WebAPIs and not for my OWIN ones.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net mvc - How do I enable Application Insights server telemetry on...

asp.net-mvc asp.net-web-api katana azure-application-insights
Rectangle 27 1

Are you sure your database server is configured, the service broker is enable and your user has all the permission required? In order to use SqlDependency it requires Service Broker. So you have to enable Service Broker on the database and check the minimum database permission required

asp.net mvc - My connection string is not working for signalR - Stack ...

asp.net-mvc entity-framework visual-studio-2012
Rectangle 27 4

Below is our implementation of a OWIN Middleware for Application Insights.

/// <summary>
/// Extensions to help adding middleware to the OWIN pipeline
/// </summary>
public static class OwinExtensions
{
    /// <summary>
    /// Add Application Insight Request Tracking to the OWIN pipeline
    /// </summary>
    /// <param name="app"><see cref="IAppBuilder"/></param>
    public static void UseApplicationInsights(this IAppBuilder app) => app.Use(typeof(ApplicationInsights));

}

/// <summary>
/// Allows for tracking requests via Application Insight
/// </summary>
public class ApplicationInsights : OwinMiddleware
{

    /// <summary>
    /// Allows for tracking requests via Application Insight
    /// </summary>
    /// <param name="next"><see cref="OwinMiddleware"/></param>
    public ApplicationInsights(OwinMiddleware next) : base(next)
    {
    }

    /// <summary>
    /// Tracks the request and sends telemetry to application insights
    /// </summary>
    /// <param name="context"><see cref="IOwinContext"/></param>
    /// <returns></returns>
    public override async Task Invoke(IOwinContext context)
    {
        // Start Time Tracking
        var sw = new Stopwatch();
        var startTime = DateTimeOffset.Now;
        sw.Start();

        await Next.Invoke(context);

        // Send tracking to AI on request completion
        sw.Stop();

        var request = new RequestTelemetry(
            name: context.Request.Path.Value,
            startTime: startTime,
            duration: sw.Elapsed,
            responseCode: context.Response.StatusCode.ToString(),
            success: context.Response.StatusCode >= 200 && context.Response.StatusCode < 300
            )
        {
            Url = context.Request.Uri,
            HttpMethod = context.Request.Method
        };

        var client = new TelemetryClient();
        client.TrackRequest(request);

    }
}

Looks pretty good, clean and simple. I don't see any key property though, how does the AI server knows which application to add the telemetry to? Is it based on that Name parameter on the telemetry request?

@julealgon The instrumentation key is read from the ApplicationInsights.config file. I tried this solution, and it worked perfectly!

asp.net mvc - How do I enable Application Insights server telemetry on...

asp.net-mvc asp.net-web-api katana azure-application-insights
Rectangle 27 2

The [RequireHttps] attribute is inherited, so you could create a base controller, apply the attribute to that, and then derive all your controllers from that base.

[RequireHttps]
public abstract class BaseController : Controller
{}

public class HomeController : BaseController
{}

public class FooController : BaseController
{}

that would be even more work then adding the attribute to each controller, I was looking for less work? Maybe some general attribute setting or something?

Not a lot of work. A simple find-and-replace on "Controller : Controller", and replace with "Controller : BaseController", across the project in visual studio should do the trick.

ok well it would almost be the same amount of work as creating the attribute above each controller, nonetheless I was looking for a different solution. If there is one...

asp.net mvc - How do I enable ssl for all controllers in mvc applicati...

asp.net-mvc oauth-2.0 asp.net-mvc-5 ssl-certificate openid
Rectangle 27 1

The UI is a bit different in the newer versions of Windows Server. Here is where you have to enable ASP.Net in order to get it working on IIS

.net 4.0 - ASP.NET MVC on IIS 7.5 - Stack Overflow

.net-4.0 iis-7.5