How do you set the content type for a WebMatrix/Razor Response? - content-type

I'd like to return some XML instead of HTML in my WebMatrix cshtml file? How do you change the content type header?

Use the Response.ContentType property at the top of your .cshtml file then include the XML in the content of the view:
#{
Response.ContentType = "application/xml";
}
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial>415-123-4567</Dial>
</Response>

At the top of your Razor file, set the ContentType of the Response object:
#{
Response.ContentType = "application/xml";
}
... xml here ...

If you are using ASP.NET MVC, you can choose to make the change in your action method in the controller, like so:
public ActionResult MyAction() {
Response.ContentType = "text/xml";
return View();
}

Related

how to make the response as .txt file from #Responsebody annotation using the spring3.0

![enter image description here][1]
can any one please explain me how to achieve this output using spring 3.x
when i clicked on a button i want to submit the data to the server and getting the response as text(.txt) file from the spring controller 3.x using the #ResponseBody annotation...
Try to write your #ResponseBody method like this
#ResponseBody
#RequestMapping(value ="/txt" )
public String txtResponse(HttpServletResponse response){
String fileName = "a.txt";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
String content = "This is txt content";
return content;
}
This looks very similar to:
Spring MVC 3 Return Content-Type: text/plain and
Who sets response content-type in Spring MVC (#ResponseBody)
You should be able to set the Content-Type header of your response via #RequestMapping:
#RequestMapping(..., produces = org.springframework.http.MediaType.TEXT_PLAIN)
Which requires the client to pass in a Content-Type header to match.
Or by setting the header directly on your response object in your service method, like in: https://stackoverflow.com/a/5268157/1546662.
Or by adding a new message converter to the spring context, as noted in: https://stackoverflow.com/a/3617594/1546662
A better solution seems
public ResponseEntity<Resource> exportTemplate() throws IOException {
return ResponseEntity.ok().header("Content-Disposition", "inline;filename=" + "filename.txt")
.body(new ByteArrayResource(new pojoObject()));
}

Create Text File in Memory and return it over ajax, possible?

I can create a text file easily enough but I want to avoid having to keep the file on the server.
How can I create a text file in memory and return it over ajax so the file itself is returned and no file is kept on server? It doesn't need to be ajax but I want to avoid a postback if at all possible.
You can use below code to download text file in webforms
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
tw.Flush();
var bytes = ms.GetBuffer();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=test.txt");
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.ContentType = "text/plain";
Response.BinaryWrite(bytes);
Vijay's answer is correct if you're using either MVC or WebForms.
About preventing postback, You don't have to use ajax to prevent postback.
If you're using MVC, You just have to use window.location and point it to your action method in js. Something like:
// In your controller:
public class HomeController : Controller
{
public FileResult GetFile2(int id)
{
if (SomeCondition)
{
return null;
}
var fileName = "MyResult.txt";
var content = "Here's the result";
var contentType = "text/plain";
return File(Encoding.ASCII.GetBytes(content), contentType, fileName);
}
// And in your view/js file:
window.location.href = ('/Home/GetFile?id=1');
And if you're using webforms, I think best way is to create a HttpHandler to handle download links. A good tutorial can be found here.

How to get filename to from controller in asp.net mvc

After I uploaded file using file uplaod control, and assigning it's name in controller, i need to get that file name in view. Also with that file name how to delete that file in my local drive(which is previously uploaded).
thanks.
check it please
public ActionResult SaveFile(HttpPostedFileBase FileUpload)
{
string path = string.Empty;
if (FileUpload != null)
if (FileUpload.ContentLength > 0)
{
fileName = Path.GetFileName(FileUpload.FileName);
path = Path.Combine(Server.MapPath("~/App_Data/Documents"), fileName);
FileUpload.SaveAs(path);
}
return View();
}
and don't forget to add enctype = "multipart/form-data" attribute to form
to can use this jQuery plugin to upload file via ajax jQuery File Upload in ASP.NET MVC

How to change returned ContentType in ASP.NET MVC controller (ActionResult)

I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile.
Method returns view of users control (ASCX) which contain JavaScript variables.
When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript
public ActionResult ControlsLangJsFile()
{
return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
}
How do i achieve this?
Users control doesn't accept ContentType="text/xml"
Solution:
public ActionResult ControlsLangJsFile()
{
Response.ContentType = "text/javascript";
return View("~/Views/Dictionary/ControlsLangJsFile.ascx");
}
I had this same question while building a razor view with JS in it and attempted to use #jmav's solution:
public ActionResult Paths()
{
Response.ContentType = "text/javascript"; //this has no effect
return View();
}
That doesn't work when you are returning a View(). It seems that the view rendering sets the content type itself despite what is assigned in the controller method.
Instead, make the assignment in the view code itself:
// this lives in viewname.cshtml/vbhtml
#{
this.Response.ContentType = "text/javascript";
}
// script stuff...
Like this, just change the content type accordingly:
ASP.NET MVC and text/xml content type
Try:
return Json(new
{
uCode = SysContext.CurrentUserCode,
uPwd = SysContext.CurrentUserPwd,
rMe = SysContext.RememberMe
}, "application/json", JsonRequestBehavior.AllowGet);

ASP.NET Return image from .aspx link

Is it possible to output an image (or any file type) to a download link when a user clicks on a link from another ASP.NET page?
I have the file name and byte[].
Get File
...where getfile returns the file instead of going to the getfile.aspx page.
You would want .ashx for that really ;)
public class ImageHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
var myImage = GetImageSomeHow();
ctx.Response.ContentType = "image/png";
ctx.Response.OutputStream.Write(myImage);
}
}
How to Create Text Image on the fly with ASP.NET
Something like this:
string Path = Server.MapPath(Request.ApplicationPath + "\image.jpg");
Bitmap bmp = CreateThumbnail(Path,Size,Size);
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
Here is how I have done this in the past:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", string.Format("inline;filename=\"{0}.pdf\"",Guid.NewGuid()));
Response.ContentType = #"application/pdf";
Response.WriteFile(path);
Yeah, you have to clear the response completely and replace it with the image byte data as a string, and you need to make sure to set the response header for content-type according to the type of image
Yes, this is possible. There are two parts of the Response object you need to set: the Content-Type and the HTTP Header. The MSDN documentation has the details on the response object but the main concept is pretty simple. Just set the code to something like this (for a Word doc).
Response.ContentType="application/ms-word";
Response.AddHeader("content-disposition", "attachment; filename=download.doc");
There is a more complete example here
the codebehind code for getfile.aspx has to have a content-type and the browser will know that it is an image or a unknown file and will let you save it.
In asp.net you can set the ContentType by using the Response object, i.e.
Response.ContentType = "image/GIF"
Here you have a tutorial for dynamically generated image
ashx...
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext ctx)
{
string path = ".....jpg";
byte[] imgBytes = File.ReadAllBytes(path);
if (imgBytes.Length > 0)
{
ctx.Response.ContentType = "image/jpeg";
ctx.Response.BinaryWrite(imgBytes);
}
}
public bool IsReusable
{
get {return false;}
}
}

Resources