Search code examples
angularasp.net-coreasp.net-routing

ASP .Net Core + Angular 2 routing


I have a controller that returns partial views, which then are used as an Angular 2 templateUrl.

For Example:

Angular component:

@Component({
    selector: 'my-app',
    templateUrl:'/partials/index',

Controller:

 public class PartialsController : Controller
    {

        public IActionResult Index()
        {
            return PartialView();
        }
    }

Is there a way to configure the routes in such a way that Angular 2 can still get the html from the controller, but manually typing the address in a browser(www.abc.com/partials/index) returns either the default controller or "not found" instead of the partial view?

This is the current route config :

app.UseMvc(config =>
            {
                config.MapRoute(
                  name: "Default",
                  template: "{controller}/{action}/{id?}",
                  defaults: new { controller = "Home", action = "Index" }
                  );
                config.MapRoute(
                 name: "angular",
                 template: "{*anything}",
                 defaults: new { controller = "Home", action = "Index" }
                 );
            }); 

The "angular" route is needed for Angular routing to work with copy-pasting addresses from the browser.


Solution

  • You can write an action filter to handle the situation.

     public class OnlyAjaxAttribute : ActionFilterAttribute
     {
        public OnlyAjaxAttribute()
        {
    
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var accepts = context.HttpContext.Request.Headers["Accept"].ToString();
            if (accepts.Contains("text/html"))
            {
                context.Result = new HttpStatusCodeResult(404);
            }
            base.OnActionExecuting(context);
        }
    }
    [OnlyAjax]
    public class PartialsController : Controller
    {
    
        public IActionResult Index()
        {
            return PartialView();
        }
    }