Tuesday, February 7, 2017

Something about Asp.net Core/MVC

This is something that you should know about Asp.net Core:

1) To create a link that points to the correct virtual directory, you can use the following:

  <a href="~/api/mybook">See my books</a>

OR

   var s = " root is= " + Url.Content("~/");

2) To expose the controller class to the desired URL path, you have to add the "Route" class attribute. In the following case, "MyBook" service is accessible through "http://localhost:1234/api/MyBook" while "Values" is accessible through "http://localhost:1234/values/"

   [Route("api/[controller]")
   public class MyBookController : Controller {..}

    [Route("[controller]")]
    public class ValuesController : Controller {..}


In Startup.cs:

            app.UseMvc(routes =>
            {              
                // set the default route
                routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });

3) To publish the static files, you must called out the NuGet and then add the reference to this library "Microsoft.AspNetCore.StaticFiles". After that, you will be able to use the code in Startup.Configure() proc:

   app.UseStaticFiles();

4) To setup the application in IIS, first, you need to add an application pool with "No Managed Code" option. Then, publish a new virtual application that points to the output path. For example,

   src\WebApplication1\bin\Release\PublishOutput

5)

5.1) To return the HTML content, you must return the View() and the Index.cshtml file must be stored in the Views\MyBook folder.

        [HttpGet]
        public ActionResult Index()
        {
            var l = this._my_book.GetList();
            return View(l);
        }

5.2) To return the value as plain content type:

       [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value=" + id.ToString();
        }

5.3) To return the data in JSON format:

        [HttpGet("{id}", Name = "GetTodo")]
        public IActionResult GetById(string id)
        {
            var item = TodoItems.Find(id);
            if (item == null)
            {               
                return NotFound();
            }

            return new ObjectResult(item);
        }

6) Receiving the dynamic JObject param:

          [HttpPost]
          public System.Net.Http.HttpResponseMessage Post([FromBody]Newtonsoft.Json.Linq.JObject value)
          {
             //...
          }

7)

protected bool CheckStatus304(DateTime lastModified)
        {
            //http://weblogs.asp.net/jeff/304-your-images-from-a-database
            if (!String.IsNullOrEmpty(Request.Headers["If-Modified-Since"]))
            {
                CultureInfo provider = CultureInfo.InvariantCulture;
                var lastMod = DateTime.ParseExact(Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
                if (lastMod == lastModified.AddMilliseconds(-lastModified.Millisecond))
                {
                    Response.StatusCode = 304;
                    //Response.StatusDescription = "Not Modified";
                    return true;
                }
            }

            //Response.Cache.SetCacheability(HttpCacheability.Public);
            //Response.Cache.SetLastModified(lastModified);

            //use this instead of the above:
            //string timeString = lastModified.ToUniversalTime().ToString("R");           
            //Response.Headers.Append("Last-Modified", timeString);

            return false;
        }