1

I am trying to get the URL of some resources I embedded in a class library I made. There is one javascript and one css resource. I need to be able to add these to specific razor views so that is where I'd like to access them. If I can just get the correct URL for these resources then I should be fine.

I'm using MVC .Net Framework 4.5.2

What I've Tried

1

<script type="text/javascript" src="Default.Namespace.javascript.jsFile.js"></script>

result:

Unable to find file at the specified location http://localhost:12345/Default.Namespace.javascript.jsFile.js

2

<script type="text/javascript" src="@new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream("Defalut.Namespace.javascript.jsFile.js"), "text/javascript")"></script>

result:

<script type="text/javascript" src="System.Web.Mvc.FileStreamResult"></script>

1 Answer 1

3

I am afraid you are trying to do something that is not possible. Embedded resources has no path. It is EMBEDDED into an assembly.

Option 1:

You may want to create new Controller and handle distribution of embedded resources there.

public class ResourceController : Controller
{
    public ActionResult Css([Required]string filename)
    {
        return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream("Defalut.Namespace.javascript." + filename), "text/javascript");
    }

    public ActionResult Js([Required]string filename)
    {
        return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream("Defalut.Namespace.css." + filename), "text/css");
    }
}

And reference controller action(s).

<script type="text/javascript" src="@Url.Action("Js","Resource", new { filename = "jsFile.js" })"></script>
<link rel="stylesheet" type="text/css" href="@Url.Action("Css","Resource", new { filename = "cssFile.css" })">

You may want to deal with disposing stream instance and possible states inside the controller action. Embedded resource not found for example. Also you can cache results with OutputCache attribute to speed things up.

Option 2:

During the web app startup read embedded resources and save them to folder inside web app, then reference it.

Related links:

OutputCacheAttribute Class

Sign up to request clarification or add additional context in comments.

1 Comment

This was very helpful. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.