c# - Returning JSON as a .json file -


i trying following code return json file instead of returning aspx file. have used similar code in php works, however, can not duplicate in c#. respond .json file.

 string json = jsonconvert.serializeobject(output, formatting.indented);         response.headers.add("content-type", "application/json; charset=utf-8");         response.headers.add("expires"," mon, 26 jul 1997 05:00:00 gmt");          response.headers.add("pragma.","no-cache");         response.cache.setnostore(); 

the output fine, want recognized .json file.

try using:

// note case response.headers.add("content-type", "application/json; charset=utf-8");  

or better:

response.contenttype = "application/json; charset=utf-8"; 

for seem do, i'd recommend using ihttphandler instead of aspx page. can configure 1 have json extension (although extension should not important). here example:

public class customhttphandler : ihttphandler {     // return true reuse (cache server-side) result      // same request parameters or false, otherwise      public bool isreusable { { return true; } }      public void processrequest(httpcontext context)     {         var response = context.response;         // response must     } 

and configure in web config:

<configuration>     </system.web>         <httphandlers>             <remove verb="*" path="*.asmx" />             <add verb="*"                   path="*.asmx"                   validate="false" type="system.web.script.services.scripthandlerfactory, system.web.extensions" />             <add verb="*"                   path="*_appservice.axd"                   validate="false"                   type="system.web.script.services.scripthandlerfactory, system.web.extensions" />             <add verb="get,head"                   path="scriptresource.axd"                   type="system.web.handlers.scriptresourcehandler, system.web.extensions" validate="false" />             <!-- handler here: -->             <add verb="get"                   path="customhttphandler.json"                   type="yourapp.customhttphandler, yourapp" />         </httphandlers>      </system.web> </configuration> 

you can play verb make handle accessible get/post or other request types, use "*" all. handler accessible "~/customhttphandler.json" - note json extension added (the original .ashx). still have put content type headers in response though.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -